Skip to main content

brokk_bifrost_cpp/graph/
extractor.rs

1use crate::call_match::{
2    CppArgType, cpp_filter_candidates_by_args_with_parameter_types, cpp_forwarding_call_argument,
3    cpp_literal_arg_type, cpp_type_text_pointer_depth, normalize_cpp_type_name,
4};
5use crate::declarations::{
6    CppSentinelRecoveredClass, cpp_active_template_type_parameter, cpp_export_macro_token,
7    cpp_sentinel_recovered_scope_for_node, enclosing_cpp_namespace_nodes,
8    is_recovered_exported_class_base_type_node, node_text, normalize_cpp_whitespace,
9    recovered_macro_return_type_node,
10};
11use crate::graph::CppGraphSource;
12use crate::graph::callable_definitions_share_identity_evidence as cpp_callable_definitions_share_identity_evidence;
13use crate::graph::callable_definitions_share_identity_evidence_with_visibility as cpp_callable_definitions_share_identity_evidence_with_visibility;
14use crate::graph::hits::{
15    enclosing_context, is_member_field_own_declarator, push_declaration_reference_hit,
16    push_declared_reference_hit, push_definition_hit, push_hit, push_recovered_definition_hit,
17    push_recursive_reference_hit, push_reference_hit_range, push_self_receiver_hit, push_type_hit,
18    push_type_hit_range, push_unproven_definition_hit, push_unproven_hit,
19    push_unproven_reference_hit_range,
20};
21use crate::graph::resolver::*;
22use crate::graph::syntax::{
23    function_macro_replacement_span, object_macro_replacement_type_references,
24    qualified_callable_value, receiver_is_self_like,
25};
26use crate::graph_support::CppSource;
27use brokk_bifrost_core::analyzer::fq_name::segment_interner;
28use brokk_bifrost_core::analyzer::prepared_syntax::PreparedSyntaxTree;
29use brokk_bifrost_core::analyzer::query_token::QueryToken;
30use brokk_bifrost_core::analyzer::semantic_diagnostics::contains_node as node_is_within;
31use brokk_bifrost_core::analyzer::tree_walk::{
32    ParentIndex, WalkControl, children_iter, first_named_child_of_kind, parent_if_field,
33    push_named_children_reversed, root_node, walk_named_tree_preorder,
34};
35use brokk_bifrost_core::analyzer::usages::common::same_node;
36use brokk_bifrost_core::analyzer::usages::inverted_edges::ClassRangeIndex;
37use brokk_bifrost_core::analyzer::usages::local_inference::{
38    LocalInferenceConfig, LocalInferenceEngine, SymbolResolution,
39};
40use brokk_bifrost_core::analyzer::usages::model::{UsageHit, UsageHitSurface};
41use brokk_bifrost_core::analyzer::{CodeUnit, ProjectFile, Range};
42use brokk_bifrost_core::hash::{HashMap, HashSet};
43#[cfg(any(test, feature = "test-support"))]
44use std::cell::Cell;
45use std::cell::RefCell;
46use std::collections::BTreeSet;
47use std::sync::Arc;
48use std::time::Instant;
49use tree_sitter::Node;
50
51#[cfg(any(test, feature = "test-support"))]
52thread_local! {
53    pub static LEXICAL_SCOPE_RECONSTRUCTIONS_FOR_TEST: Cell<usize> = const { Cell::new(0) };
54    static TYPE_REFERENCE_CANDIDATE_SCAN_COUNT: Cell<usize> = const { Cell::new(0) };
55}
56
57#[cfg(any(test, feature = "test-support"))]
58pub fn reset_type_reference_candidate_scan_count_for_test() {
59    TYPE_REFERENCE_CANDIDATE_SCAN_COUNT.with(|count| count.set(0));
60}
61
62#[cfg(any(test, feature = "test-support"))]
63pub fn type_reference_candidate_scan_count_for_test() -> usize {
64    TYPE_REFERENCE_CANDIDATE_SCAN_COUNT.with(Cell::get)
65}
66
67pub struct ScanState<'a> {
68    pub max_usages: usize,
69    pub hits: &'a mut BTreeSet<UsageHit>,
70    pub unproven_hits: &'a mut BTreeSet<UsageHit>,
71    pub raw_match_count: &'a mut usize,
72    pub limit_exceeded: &'a mut bool,
73}
74
75pub struct ScanCtx<'a> {
76    pub analyzer: CppGraphSource<'a>,
77    pub visibility: &'a VisibilityIndex<'a>,
78    pub file: &'a ProjectFile,
79    pub source: &'a str,
80    /// The parent of every node in the file being scanned, recorded by one
81    /// downward pass when the scan starts. `Node::parent` recovers a parent by
82    /// re-descending from the root, so an ancestor climb is quadratic in depth
83    /// and the scan climbs from more than a dozen call sites per visited node
84    /// (#1927, #3097).
85    pub ancestry: ParentIndex<'a>,
86    ordinary_type_imports: OrdinaryTypeImportCell,
87    recovered_sentinel_classes: &'a [CppSentinelRecoveredClass],
88    class_ranges: Option<&'a ClassRangeIndex>,
89    pub line_starts: &'a [usize],
90    pub spec: &'a TargetSpec,
91    pub target_group: &'a HashSet<CodeUnit>,
92    pub has_proven_visible_type_target: bool,
93    uses_c_semantics: bool,
94    type_reference_component_names: HashSet<String>,
95    pub target_declaration_ranges: Vec<Range>,
96    target_macro_declaration_bytes: Vec<usize>,
97    pub bindings: LocalInferenceEngine<CppScanBinding>,
98    local_shadows: LocalInferenceEngine<()>,
99    using_enum_owners: ScopedUsingEnumOwners,
100    semantic_using_enum_owners: SemanticUsingEnumOwners,
101    needs_using_enum_member_resolution: bool,
102    pub hits: &'a mut BTreeSet<UsageHit>,
103    pub unproven_hits: &'a mut BTreeSet<UsageHit>,
104    pub raw_match_count: &'a mut usize,
105    pub max_usages: usize,
106    pub external_hit_count: usize,
107    pub limit_exceeded: &'a mut bool,
108    pub enclosing_cache: RefCell<HashMap<(usize, usize), EnclosingContext>>,
109    pub enclosing_owner_cache: RefCell<HashMap<CodeUnit, Option<CodeUnit>>>,
110    lexical_scope_cache: LexicalScopeCache,
111    lexical_free_function_cache: RefCell<HashMap<(String, String), bool>>,
112    member_owner_cache: RefCell<HashMap<CodeUnit, EnclosingMemberOwnerResolution>>,
113    global_field_internal_linkage_cache: RefCell<HashMap<CodeUnit, bool>>,
114    receiver_canonical_type_cache: RefCell<HashMap<CodeUnit, Option<CodeUnit>>>,
115}
116
117impl ScanCtx<'_> {
118    fn recovered_sentinel_scope(&self, node: Node<'_>) -> Option<Vec<String>> {
119        cpp_sentinel_recovered_scope_for_node(node, self.source, self.recovered_sentinel_classes)
120    }
121}
122
123#[derive(Clone, Default)]
124pub struct EnclosingContext {
125    pub enclosing: Option<CodeUnit>,
126    pub owner: Option<CodeUnit>,
127}
128
129pub fn prepare_file(
130    cpp: &dyn CppSource,
131    token: QueryToken<'_>,
132    file: &ProjectFile,
133) -> Option<Arc<PreparedSyntaxTree>> {
134    cpp.prepared_syntax(token, file)
135}
136
137#[allow(clippy::too_many_arguments)]
138pub fn scan_prepared_file(
139    analyzer: &CppGraphSource<'_>,
140    visibility: &VisibilityIndex<'_>,
141    file: &ProjectFile,
142    prepared: &PreparedSyntaxTree,
143    recovered_sentinel_classes: &[CppSentinelRecoveredClass],
144    class_ranges: Option<&ClassRangeIndex>,
145    spec: &TargetSpec,
146    target_group: &HashSet<CodeUnit>,
147    state: &mut ScanState<'_>,
148) {
149    if *state.limit_exceeded {
150        return;
151    }
152    let needs_using_enum_member_resolution = spec.enum_owner_kind == EnumOwnerKind::Scoped;
153    let has_proven_visible_type_target = spec.kind == TargetKind::Type
154        && (target_group.iter().any(|target| {
155            same_logical_symbol(target, &spec.target)
156                && visibility.is_physically_visible(file, target)
157        }) || {
158            let candidates = visibility
159                .visible_identifier_candidates(file, spec.target.identifier())
160                .collect::<Vec<_>>();
161            visibility.c_tag_declaration_family_matches_target(
162                analyzer,
163                file,
164                &candidates,
165                &spec.target,
166            )
167        });
168    if spec.kind == TargetKind::Type
169        && !has_proven_visible_type_target
170        && visibility
171            .visible_identifier_candidates(file, spec.target.identifier())
172            .any(|candidate| {
173                candidate != &spec.target
174                    && !target_group.contains(candidate)
175                    && same_logical_symbol(candidate, &spec.target)
176                    && visibility.is_physically_visible(file, candidate)
177                    && !visibility.c_tag_declaration_family_matches_target(
178                        analyzer,
179                        file,
180                        std::slice::from_ref(&candidate),
181                        &spec.target,
182                    )
183            })
184    {
185        return;
186    }
187    let macro_target_declaration_ranges = if spec.kind == TargetKind::Macro {
188        analyzer.ranges(&spec.target)
189    } else {
190        Vec::new()
191    };
192    let target_declaration_ranges = if spec.kind == TargetKind::Type {
193        target_group
194            .iter()
195            .filter(|target| target.source() == file && same_logical_symbol(target, &spec.target))
196            .flat_map(|target| analyzer.ranges(target))
197            .collect()
198    } else if spec.target.source() == file {
199        if spec.kind == TargetKind::Macro {
200            macro_target_declaration_ranges.clone()
201        } else {
202            analyzer.ranges(&spec.target)
203        }
204    } else {
205        Vec::new()
206    };
207    let target_macro_declaration_bytes = if spec.kind == TargetKind::Macro {
208        visibility.macro_declaration_bytes(&spec.target, &macro_target_declaration_ranges)
209    } else {
210        Vec::new()
211    };
212    let type_reference_component_names = if spec.kind == TargetKind::Type {
213        visibility.visible_type_reference_component_names_for_target(analyzer, file, &spec.target)
214    } else {
215        HashSet::default()
216    };
217    if spec.kind == TargetKind::Type
218        && !file_may_reference_type_target(
219            prepared.tree().root_node(),
220            prepared.source(),
221            analyzer,
222            visibility,
223            file,
224            &spec.target,
225            &type_reference_component_names,
226        )
227    {
228        return;
229    }
230    let ordinary_type_imports = initialized_ordinary_type_imports(
231        prepared.tree().root_node(),
232        analyzer,
233        visibility,
234        file,
235        prepared.source(),
236    );
237    let external_hit_count = state
238        .hits
239        .iter()
240        .filter(|hit| hit.kind.included_in(UsageHitSurface::ExternalUsages))
241        .count();
242    let mut ctx = ScanCtx {
243        analyzer: *analyzer,
244        visibility,
245        file,
246        source: prepared.source(),
247        ancestry: ParentIndex::new(prepared.tree().root_node()),
248        ordinary_type_imports,
249        recovered_sentinel_classes,
250        class_ranges,
251        line_starts: prepared.line_starts(),
252        spec,
253        target_group,
254        has_proven_visible_type_target,
255        uses_c_semantics: analyzer.reference_uses_c_semantics(file),
256        type_reference_component_names,
257        target_declaration_ranges,
258        target_macro_declaration_bytes,
259        bindings: LocalInferenceEngine::new(LocalInferenceConfig::default()),
260        local_shadows: LocalInferenceEngine::new(LocalInferenceConfig::default()),
261        using_enum_owners: ScopedUsingEnumOwners::new(),
262        semantic_using_enum_owners: SemanticUsingEnumOwners::new(),
263        needs_using_enum_member_resolution,
264        hits: state.hits,
265        unproven_hits: state.unproven_hits,
266        raw_match_count: state.raw_match_count,
267        max_usages: state.max_usages,
268        external_hit_count,
269        limit_exceeded: state.limit_exceeded,
270        enclosing_cache: RefCell::new(HashMap::default()),
271        enclosing_owner_cache: RefCell::new(HashMap::default()),
272        lexical_scope_cache: LexicalScopeCache::new(visibility, file),
273        lexical_free_function_cache: RefCell::new(HashMap::default()),
274        member_owner_cache: RefCell::new(HashMap::default()),
275        global_field_internal_linkage_cache: RefCell::new(HashMap::default()),
276        receiver_canonical_type_cache: RefCell::new(HashMap::default()),
277    };
278    if needs_using_enum_member_resolution {
279        collect_semantic_using_enums(prepared.tree().root_node(), &mut ctx);
280    }
281    if spec.kind == TargetKind::Macro {
282        scan_macro_nodes(prepared.tree().root_node(), &mut ctx);
283        return;
284    }
285    scan_node(prepared.tree().root_node(), &mut ctx);
286}
287
288/// Scan a macro target without maintaining the declaration and lexical state
289/// required by ordinary C and C++ symbols. Macro activation comes entirely
290/// from [`VisibilityIndex`], so rebuilding unrelated binding state at every
291/// node makes generated tables needlessly expensive.
292fn scan_macro_nodes(root: Node<'_>, ctx: &mut ScanCtx<'_>) {
293    walk_named_tree_preorder(root, true, |node| {
294        if *ctx.limit_exceeded {
295            return WalkControl::Break;
296        }
297        maybe_record_macro_hit(node, ctx);
298        WalkControl::Continue
299    });
300}
301
302enum UsingEnumDeclarationScope {
303    Block,
304    Class(CodeUnit),
305    Namespace(Vec<String>),
306    UnsupportedClass,
307}
308
309fn resolved_using_enum_declaration(
310    node: Node<'_>,
311    ctx: &ScanCtx<'_>,
312) -> Option<(CodeUnit, UsingEnumDeclarationScope)> {
313    let LexicalTypeResolution::Resolved { unit, .. } = resolve_using_enum_declaration_owner(
314        node,
315        &ctx.analyzer,
316        ctx.visibility,
317        &ctx.ordinary_type_imports,
318        ctx.file,
319        ctx.source,
320    ) else {
321        return None;
322    };
323    Some((unit, using_enum_declaration_scope(node, ctx)))
324}
325
326fn using_enum_declaration_scope(node: Node<'_>, ctx: &ScanCtx<'_>) -> UsingEnumDeclarationScope {
327    let mut current = ctx.ancestry.parent(node);
328    while let Some(parent) = current {
329        if matches!(
330            parent.kind(),
331            "compound_statement"
332                | "function_definition"
333                | "lambda_expression"
334                | "for_statement"
335                | "while_statement"
336                | "if_statement"
337        ) {
338            return UsingEnumDeclarationScope::Block;
339        }
340        if matches!(
341            parent.kind(),
342            "class_specifier" | "struct_specifier" | "union_specifier"
343        ) {
344            let resolution = enclosing_lexical_scope_components(
345                node,
346                &ctx.analyzer,
347                ctx.visibility,
348                ctx.file,
349                ctx.source,
350            );
351            if let LexicalScopeResolution::Resolved(components) = resolution
352                && let LexicalTypeResolution::Resolved { unit, .. } =
353                    ctx.visibility.resolve_type_components_lexically(
354                        &ctx.analyzer,
355                        ctx.file,
356                        &components,
357                        true,
358                        &[],
359                    )
360            {
361                return UsingEnumDeclarationScope::Class(unit);
362            }
363            return UsingEnumDeclarationScope::UnsupportedClass;
364        }
365        current = ctx.ancestry.parent(parent);
366    }
367    UsingEnumDeclarationScope::Namespace(enclosing_namespace_components(node, ctx.source))
368}
369
370fn collect_semantic_using_enums(root: Node<'_>, ctx: &mut ScanCtx<'_>) {
371    let mut stack = vec![root];
372    while let Some(node) = stack.pop() {
373        if node.kind() == "using_declaration"
374            && let Some((unit, scope)) = resolved_using_enum_declaration(node, ctx)
375        {
376            match scope {
377                UsingEnumDeclarationScope::Block => {}
378                UsingEnumDeclarationScope::Class(class) => {
379                    ctx.semantic_using_enum_owners.import_class(class, unit);
380                }
381                UsingEnumDeclarationScope::Namespace(namespace) => {
382                    ctx.semantic_using_enum_owners.import_namespace(
383                        namespace,
384                        node.start_byte(),
385                        unit,
386                    );
387                }
388                UsingEnumDeclarationScope::UnsupportedClass => {}
389            }
390        }
391        push_named_children_reversed(node, &mut stack);
392    }
393}
394
395fn scan_node(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
396    if *ctx.limit_exceeded {
397        return;
398    }
399    let enters_scope = matches!(
400        node.kind(),
401        "compound_statement"
402            | "function_definition"
403            | "lambda_expression"
404            | "for_statement"
405            | "for_range_loop"
406            | "while_statement"
407            | "if_statement"
408    );
409    let enters_using_enum_scope = ctx.needs_using_enum_member_resolution
410        && (enters_scope
411            || matches!(
412                node.kind(),
413                "namespace_definition" | "class_specifier" | "struct_specifier" | "union_specifier"
414            ));
415    if enters_scope {
416        ctx.bindings.enter_scope();
417        ctx.local_shadows.enter_scope();
418    }
419    if enters_using_enum_scope {
420        ctx.using_enum_owners.enter_scope();
421    }
422
423    seed_declarations(node, ctx);
424    maybe_record_hit(node, ctx);
425
426    let translation_unit = node.kind() == "translation_unit";
427    let mut fractured_function_scope = false;
428    let mut cursor = node.walk();
429    for child in node.named_children(&mut cursor) {
430        if translation_unit && fractured_function_scope && child.kind() == "ERROR" {
431            ctx.bindings.exit_scope();
432            ctx.local_shadows.exit_scope();
433            fractured_function_scope = false;
434        }
435        scan_node(child, ctx);
436        if *ctx.limit_exceeded {
437            break;
438        }
439        if translation_unit
440            && macro_fractured_function(child)
441            && macro_fracture_boundary(child).is_some()
442        {
443            if fractured_function_scope {
444                ctx.bindings.exit_scope();
445                ctx.local_shadows.exit_scope();
446            }
447            ctx.bindings.enter_scope();
448            ctx.local_shadows.enter_scope();
449            seed_fractured_function_prefix(child, ctx);
450            fractured_function_scope = true;
451        }
452    }
453    if fractured_function_scope {
454        ctx.bindings.exit_scope();
455        ctx.local_shadows.exit_scope();
456    }
457
458    if enters_scope {
459        ctx.bindings.exit_scope();
460        ctx.local_shadows.exit_scope();
461    }
462    if enters_using_enum_scope {
463        ctx.using_enum_owners.exit_scope();
464    }
465}
466
467fn macro_fractured_function(node: Node<'_>) -> bool {
468    if node.kind() != "function_definition" {
469        return false;
470    }
471    let Some(body) = node.child_by_field_name("body") else {
472        return false;
473    };
474    let mut stack = vec![body];
475    while let Some(current) = stack.pop() {
476        if matches!(current.kind(), "preproc_def" | "preproc_function_def") {
477            return true;
478        }
479        let mut cursor = current.walk();
480        stack.extend(current.named_children(&mut cursor));
481    }
482    false
483}
484
485/// Return the recovery boundary following a fractured macro-generated callable.
486pub fn macro_fracture_boundary(node: Node<'_>) -> Option<usize> {
487    let first_orphan = node.next_named_sibling()?;
488    if !matches!(
489        first_orphan.kind(),
490        "expression_statement"
491            | "if_statement"
492            | "for_statement"
493            | "while_statement"
494            | "do_statement"
495            | "return_statement"
496    ) {
497        return None;
498    }
499    let mut sibling = Some(first_orphan);
500    while let Some(current) = sibling {
501        if current.kind() == "ERROR" {
502            return Some(current.end_byte());
503        }
504        if matches!(
505            current.kind(),
506            "function_definition" | "declaration" | "type_definition"
507        ) {
508            return None;
509        }
510        sibling = current.next_named_sibling();
511    }
512    None
513}
514
515fn seed_fractured_function_prefix(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
516    let cutoff = node.end_byte().saturating_sub(1);
517    seed_fractured_active_path(node, cutoff, ctx);
518}
519
520fn seed_fractured_active_path(node: Node<'_>, cutoff: usize, ctx: &mut ScanCtx<'_>) {
521    if node.start_byte() >= cutoff {
522        return;
523    }
524    let enters_scope = matches!(
525        node.kind(),
526        "compound_statement"
527            | "function_definition"
528            | "lambda_expression"
529            | "for_range_loop"
530            | "for_statement"
531            | "while_statement"
532            | "if_statement"
533            | "class_specifier"
534            | "struct_specifier"
535            | "union_specifier"
536    );
537    if enters_scope && !(node.start_byte() <= cutoff && cutoff < node.end_byte()) {
538        return;
539    }
540    seed_declarations(node, ctx);
541    let mut cursor = node.walk();
542    for child in node.named_children(&mut cursor) {
543        if child.start_byte() >= cutoff {
544            break;
545        }
546        seed_fractured_active_path(child, cutoff, ctx);
547    }
548}
549
550fn seed_declarations(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
551    if crate::declarations::is_direct_recovered_exported_class_field_declaration(node, ctx.source)
552        || (ctx.spec.kind != TargetKind::Type
553            && indexed_recovered_class_field_declaration(node, ctx))
554    {
555        return;
556    }
557    match node.kind() {
558        "parameter_declaration" | "optional_parameter_declaration" => seed_typed_binding(node, ctx),
559        "declaration" | "field_declaration" => seed_variable_declaration(node, ctx),
560        "for_range_loop" => seed_range_binding(node, ctx),
561        "expression_statement" => seed_function_macro_local_binding(node, ctx),
562        "assignment_expression" => seed_function_macro_container_binding(node, ctx),
563        "using_declaration" => seed_using_enum(node, ctx),
564        _ => {}
565    }
566}
567
568fn seed_function_macro_local_binding(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
569    let Some(binding) = ctx
570        .visibility
571        .function_macro_local_binding(ctx.file, node, ctx.source)
572    else {
573        return;
574    };
575    if ctx.spec.kind == TargetKind::Type {
576        ctx.bindings.declare_shadow(binding.name);
577        return;
578    }
579    let normalized = normalize_cpp_type_name(&binding.type_name);
580    let unit = binding
581        .type_node
582        .and_then(|type_node| {
583            ctx.visibility
584                .resolve_type_node_result(ctx.file, type_node, ctx.source)
585                .ok()
586                .flatten()
587        })
588        .or_else(|| {
589            ctx.visibility
590                .canonical_type_for_reference(ctx.file, &normalized)
591        })
592        .or_else(|| ctx.visibility.resolve_type(ctx.file, &normalized));
593    ctx.bindings.seed_symbol(
594        binding.name,
595        CppScanBinding::from_type_name(
596            normalized,
597            unit,
598            binding.pointer_depth + cpp_type_text_pointer_depth(&binding.type_name),
599        ),
600    );
601}
602
603fn seed_function_macro_container_binding(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
604    let Some(binding) =
605        ctx.visibility
606            .function_macro_container_binding(&ctx.analyzer, ctx.file, node, ctx.source)
607    else {
608        return;
609    };
610    let normalized = normalize_cpp_type_name(&binding.type_name);
611    let unit = binding.proven_unit.clone().or_else(|| {
612        binding
613            .type_node
614            .and_then(|type_node| {
615                ctx.visibility
616                    .resolve_type_node_result(ctx.file, type_node, ctx.source)
617                    .ok()
618                    .flatten()
619            })
620            .or_else(|| ctx.visibility.resolve_type(ctx.file, &normalized))
621    });
622    if let Some(unit) = unit {
623        ctx.bindings.seed_symbol(
624            binding.name,
625            CppScanBinding::from_type_name(normalized, Some(unit), binding.pointer_depth),
626        );
627    }
628}
629
630fn indexed_recovered_class_field_declaration(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
631    if node.kind() != "declaration"
632        || !has_function_scope_ancestor(node)
633        || has_ancestor_kind(node, "lambda_expression")
634        || !(has_recovered_class_shape_ancestor(node)
635            || has_malformed_wrapper_function_definition_ancestor(node))
636    {
637        return false;
638    }
639    let context = enclosing_context(node, ctx);
640    context.enclosing.as_ref().is_some_and(CodeUnit::is_field)
641        && context.owner.as_ref().is_some_and(CodeUnit::is_class)
642}
643
644fn seed_using_enum(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
645    if !ctx.needs_using_enum_member_resolution {
646        return;
647    }
648    if let Some((unit, UsingEnumDeclarationScope::Block)) =
649        resolved_using_enum_declaration(node, ctx)
650    {
651        ctx.using_enum_owners.import(unit);
652    }
653}
654
655fn seed_variable_declaration(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
656    // Class and local-struct fields are resolved from their enclosing owner
657    // when they appear as an unqualified receiver. Seeding them into the
658    // function-wide binding scope would make same-spelled fields from sibling
659    // owners overwrite one another before the owner-aware path runs.
660    if node.kind() == "field_declaration" {
661        return;
662    }
663    let type_node = node
664        .child_by_field_name("type")
665        .or_else(|| first_type_child(node));
666    let type_text = type_node.map(|node| node_text(node, ctx.source).to_string());
667    let mut cursor = node.walk();
668    for child in node.named_children(&mut cursor) {
669        let declarator = declaration_declarator(node, child);
670        let Some(declarator) = declarator else {
671            continue;
672        };
673        let Some(name) = extract_variable_name(declarator, ctx.source) else {
674            continue;
675        };
676        if declarator.kind() == "function_declarator"
677            && !constructor_style_local_declaration(
678                ctx.visibility,
679                ctx.file,
680                ctx.source,
681                declarator,
682                type_text.as_deref(),
683                &ctx.bindings,
684            )
685        {
686            if node.kind() == "declaration" && has_function_scope_ancestor(node) {
687                ctx.local_shadows.declare_shadow(name);
688            }
689            continue;
690        }
691        if node.kind() == "declaration" && has_function_scope_ancestor(node) {
692            ctx.local_shadows.declare_shadow(name.clone());
693        }
694        if ctx.spec.kind == TargetKind::Type {
695            ctx.bindings.declare_shadow(name);
696            continue;
697        }
698        let value = child.child_by_field_name("value");
699        seed_binding_from_type_or_value(&name, type_node, value, ctx);
700    }
701}
702
703fn seed_typed_binding(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
704    if !parameter_belongs_to_callable_scope(node) {
705        return;
706    }
707    let Some((name, _, type_node)) = cpp_binding_parts(node, ctx.source) else {
708        return;
709    };
710    if has_function_scope_ancestor(node) {
711        ctx.local_shadows.declare_shadow(name.clone());
712    }
713    if ctx.spec.kind == TargetKind::Type {
714        ctx.bindings.declare_shadow(name);
715        return;
716    }
717    seed_binding_from_type_or_value(&name, type_node, None, ctx);
718}
719
720fn seed_range_binding(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
721    let Some((name, _, type_node)) = cpp_binding_parts(node, ctx.source) else {
722        return;
723    };
724    if has_function_scope_ancestor(node) {
725        ctx.local_shadows.declare_shadow(name.clone());
726    }
727    if ctx.spec.kind == TargetKind::Type {
728        ctx.bindings.declare_shadow(name);
729        return;
730    }
731    seed_binding_from_type_or_value(&name, type_node, None, ctx);
732}
733
734fn has_function_scope_ancestor(node: Node<'_>) -> bool {
735    let mut current = node.parent();
736    while let Some(parent) = current {
737        // Error recovery can wrap a complete namespace in a bogus outer
738        // `function_definition` (for example when an object-like namespace
739        // macro is parsed as a return type).  Declarations below that
740        // namespace are still namespace-scoped: do not let the malformed
741        // callable envelope seed them as local shadows.  A real function
742        // body is encountered before its enclosing namespace, so this keeps
743        // ordinary local binding detection unchanged.
744        if parent.kind() == "namespace_definition" {
745            return false;
746        }
747        if parent.kind() == "function_definition" {
748            // The malformed sentinel envelope is not a callable scope. Its
749            // body may contain a recovered namespace (or, in a smaller error
750            // tree, only an ERROR node standing in for that namespace), so
751            // declarations directly below it must remain namespace-scoped.
752            // Real nested functions are encountered first and still seed
753            // ordinary local bindings.
754            return !is_malformed_wrapper_function_definition(parent);
755        }
756        if parent.kind() == "lambda_expression" {
757            return true;
758        }
759        current = parent.parent();
760    }
761    false
762}
763
764fn seed_binding_from_type_or_value(
765    name: &str,
766    type_node: Option<Node<'_>>,
767    value: Option<Node<'_>>,
768    ctx: &mut ScanCtx<'_>,
769) {
770    if name.is_empty() {
771        return;
772    }
773    let resolved = type_node
774        .filter(|node| normalize_type_text(node_text(*node, ctx.source)) != "auto")
775        .map(|node| {
776            let text = node_text(node, ctx.source);
777            let name = normalize_cpp_type_name(text);
778            if let Some(unit) = anonymous_aggregate_owner(&ctx.analyzer, ctx.file, node) {
779                return CppScanBinding::from_type_name(
780                    name,
781                    Some(unit),
782                    cpp_type_text_pointer_depth(text),
783                );
784            }
785            // Bare type names need lexical ownership before the coarse visible-name
786            // fallback (two namespaces can each declare `CopyResult`). Template
787            // references keep the specialization-aware resolver first because a
788            // component-only lexical lookup cannot rank partial specializations.
789            let lexical_scope = ctx.recovered_sentinel_scope(node).or_else(|| {
790                if cpp_template_reference_arguments(node, ctx.source).is_some() {
791                    return None;
792                }
793                match enclosing_lexical_scope_components(
794                    node,
795                    &ctx.analyzer,
796                    ctx.visibility,
797                    ctx.file,
798                    ctx.source,
799                ) {
800                    LexicalScopeResolution::Resolved(scope) => Some(scope),
801                    LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => None,
802                }
803            });
804            let unit = lexical_scope
805                .as_deref()
806                .and_then(|scope| resolve_seed_type_node_lexically(node, ctx, scope))
807                .or_else(|| {
808                    match ctx
809                        .visibility
810                        .resolve_type_node_result(ctx.file, node, ctx.source)
811                    {
812                        Ok(Some(unit)) => Some(unit),
813                        Ok(None) => ctx
814                            .visibility
815                            .canonical_type_for_reference(ctx.file, &name)
816                            .or_else(|| ctx.visibility.resolve_type(ctx.file, &name)),
817                        Err(_) => None,
818                    }
819                });
820            CppScanBinding::from_type_name(name.clone(), unit, cpp_type_text_pointer_depth(text))
821        })
822        .or_else(|| value.and_then(|value| infer_type_from_value(value, ctx)));
823
824    if let Some(resolved) = resolved {
825        ctx.bindings.seed_symbol(name.to_string(), resolved);
826    } else if let Some(value) = value
827        && value.kind() == "identifier"
828    {
829        ctx.bindings
830            .alias_symbol(name.to_string(), node_text(value, ctx.source));
831    } else {
832        ctx.bindings.declare_shadow(name.to_string());
833    }
834}
835
836fn resolve_seed_type_node_lexically(
837    node: Node<'_>,
838    ctx: &ScanCtx<'_>,
839    scope: &[String],
840) -> Option<CodeUnit> {
841    let (components, global) = type_reference_components(node, ctx.source)?;
842    let resolution = match scan_owner_type(ctx) {
843        Some(target) => ctx.visibility.resolve_type_components_lexically_for_target(
844            &ctx.analyzer,
845            ctx.file,
846            &components,
847            global,
848            scope,
849            target,
850        ),
851        None => ctx.visibility.resolve_type_components_lexically(
852            &ctx.analyzer,
853            ctx.file,
854            &components,
855            global,
856            scope,
857        ),
858    };
859    match resolution {
860        LexicalTypeResolution::Resolved { unit, .. } => Some(unit),
861        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
862    }
863}
864
865/// The type this scan is asking about: the owner of a member target, or the
866/// target itself when it is a type.
867///
868/// C headers routinely declare one typedef name once per branch of an
869/// `#if`/`#else` pair, for example tinycthread's `mtx_t` as a Win32 struct and
870/// as `pthread_mutex_t` (#2996). The branches cannot both be compiled, so they
871/// are alternate spellings of one name rather than competing declarations, and
872/// canonicalizing without the scan's own type identity picks between them by
873/// declaration order. That ordering can bind a receiver to the branch that does
874/// not declare the queried member, which drops every reference in the branch
875/// that does. Naming the identity keeps the target-preserving rule the forward
876/// resolver already applies (`unique_type_candidate_preserving_target`).
877fn scan_owner_type<'a>(ctx: &'a ScanCtx<'_>) -> Option<&'a CodeUnit> {
878    // Target-preserving lookup can reconcile logical declarations across files.
879    // A receiver must not borrow an owner from a header its caller cannot see.
880    ctx.spec
881        .owner
882        .as_ref()
883        .filter(|owner| owner.is_class() && ctx.visibility.is_physically_visible(ctx.file, owner))
884}
885
886const MAX_RECEIVER_CALL_RESOLUTION_DEPTH: usize = 32;
887
888fn infer_type_from_value(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CppScanBinding> {
889    infer_type_from_value_with_budget(node, ctx, MAX_RECEIVER_CALL_RESOLUTION_DEPTH)
890}
891
892fn infer_type_from_value_with_budget(
893    node: Node<'_>,
894    ctx: &ScanCtx<'_>,
895    remaining_call_depth: usize,
896) -> Option<CppScanBinding> {
897    match node.kind() {
898        "new_expression" | "call_expression" if remaining_call_depth == 0 => {
899            infer_cpp_initializer_binding(
900                &ctx.analyzer,
901                ctx.visibility,
902                ctx.file,
903                ctx.source,
904                node,
905                None,
906            )
907        }
908        "new_expression" | "call_expression" => infer_cpp_initializer_binding(
909            &ctx.analyzer,
910            ctx.visibility,
911            ctx.file,
912            ctx.source,
913            node,
914            Some(&|receiver, source| {
915                receiver_type_units_with_budget(receiver, source, ctx, remaining_call_depth - 1)
916            }),
917        ),
918        "initializer_list" => None,
919        "identifier" => {
920            let resolved = ctx.bindings.resolve_symbol(node_text(node, ctx.source));
921            resolved
922                .as_precise()?
923                .iter()
924                .find(|binding| binding.unit.as_ref().is_some_and(CodeUnit::is_class))
925                .cloned()
926        }
927        _ => {
928            let text = node_text(node, ctx.source);
929            let name = normalize_cpp_type_name(text);
930            ctx.visibility
931                .resolve_type(ctx.file, &name)
932                .map(|unit| CppScanBinding::from_unit(unit, 0))
933        }
934    }
935}
936
937/// Whether a member named `identifier` can be spelled anywhere in this file's
938/// syntax.
939///
940/// Both member scans below -- [`maybe_record_method_hit`] and
941/// [`maybe_record_member_field_hit`] -- begin by comparing the terminal name
942/// of a syntax node against the target's member name, so a file whose syntax
943/// never spells that name yields neither a proven nor an unproven hit. That
944/// makes this an exact admission test rather than an approximation: candidate
945/// discovery can drop such a file without narrowing what the query proves.
946///
947/// Only tree-sitter nodes are read. Two node kinds carry text the C++ grammar
948/// does not tokenize into identifiers -- a function-like macro's `preproc_arg`
949/// replacement, which
950/// [`maybe_record_function_macro_replacement_method_hits`] recovers by its own
951/// sentinel parse, and an `ERROR` region -- so those admit on containment
952/// instead of on a token match. A `comment` is the one subtree no scan reads,
953/// so it is skipped.
954///
955/// Defined only for a plain identifier: [`name_matches_callable`] widens the
956/// comparison for an `operator` name to the `operator` token alone, and a
957/// destructor or conversion-function name is not spelled the way it is
958/// recorded. [`cpp_member_is_spelled_at_references`] is the admission side of
959/// that condition.
960pub fn cpp_syntax_may_spell_member(root: Node<'_>, source: &str, identifier: &str) -> bool {
961    debug_assert!(
962        cpp_member_is_spelled_at_references(identifier),
963        "member admission is defined only for a plain identifier: {identifier:?}"
964    );
965    let mut spelled = false;
966    walk_named_tree_preorder(root, true, |node| match node.kind() {
967        "comment" => WalkControl::SkipChildren,
968        "identifier"
969        | "field_identifier"
970        | "type_identifier"
971        | "namespace_identifier"
972        | "statement_identifier" => {
973            if node_text(node, source).trim() == identifier {
974                spelled = true;
975                WalkControl::Break
976            } else {
977                WalkControl::SkipChildren
978            }
979        }
980        "preproc_arg" | "ERROR" => {
981            if node_text(node, source).contains(identifier) {
982                spelled = true;
983                WalkControl::Break
984            } else {
985                // The node's own text covers every descendant's bytes, so a
986                // miss here is a miss for the whole subtree.
987                WalkControl::SkipChildren
988            }
989        }
990        _ => WalkControl::Continue,
991    });
992    spelled
993}
994
995/// Whether every reference to a member named `identifier` must spell it.
996///
997/// An `operator` name is matched by [`name_matches_callable`] through the bare
998/// `operator` token, and a destructor or conversion function is recorded under
999/// a name its call sites do not write, so neither admits a spelling test.
1000pub fn cpp_member_is_spelled_at_references(identifier: &str) -> bool {
1001    let mut characters = identifier.chars();
1002    characters
1003        .next()
1004        .is_some_and(|first| first.is_ascii_alphabetic() || first == '_')
1005        && characters.all(|character| character.is_ascii_alphanumeric() || character == '_')
1006        && !identifier.starts_with("operator")
1007}
1008
1009fn maybe_record_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1010    match ctx.spec.kind {
1011        TargetKind::Type => maybe_record_type_hit(node, ctx),
1012        TargetKind::Constructor => maybe_record_constructor_hit(node, ctx),
1013        TargetKind::FreeFunction => maybe_record_free_function_hit(node, ctx),
1014        TargetKind::Method => maybe_record_method_hit(node, ctx),
1015        TargetKind::GlobalField => maybe_record_global_field_hit(node, ctx),
1016        TargetKind::MemberField => maybe_record_member_field_hit(node, ctx),
1017        TargetKind::Macro => maybe_record_macro_hit(node, ctx),
1018    }
1019}
1020
1021fn maybe_record_macro_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1022    if node_text(node, ctx.source) != ctx.spec.member_name {
1023        return;
1024    }
1025    if is_ordinary_macro_reference_node(node) {
1026        if ctx.visibility.macro_binding_matches_target_declaration_at(
1027            ctx.file,
1028            &ctx.spec.member_name,
1029            node.start_byte(),
1030            ctx.spec.target.source(),
1031            &ctx.target_macro_declaration_bytes,
1032        ) {
1033            *ctx.raw_match_count += 1;
1034            push_hit(node, ctx);
1035            return;
1036        }
1037        match ctx.visibility.resolve_ordinary_macro_reference(
1038            &ctx.analyzer,
1039            ctx.file,
1040            node,
1041            ctx.source,
1042        ) {
1043            OrdinaryMacroReferenceResolution::Resolved(unit)
1044                if ctx.target_group.contains(&unit) =>
1045            {
1046                *ctx.raw_match_count += 1;
1047                push_hit(node, ctx);
1048            }
1049            OrdinaryMacroReferenceResolution::Ambiguous
1050                if ctx
1051                    .visibility
1052                    .macro_target_is_visible_candidate(ctx.file, &ctx.spec.target) =>
1053            {
1054                *ctx.raw_match_count += 1;
1055                push_unproven_hit(node, ctx);
1056            }
1057            OrdinaryMacroReferenceResolution::Resolved(_)
1058            | OrdinaryMacroReferenceResolution::Ambiguous
1059            | OrdinaryMacroReferenceResolution::Missing => {}
1060        }
1061        return;
1062    }
1063    if !matches!(
1064        node.kind(),
1065        "identifier"
1066            | "field_identifier"
1067            | "type_identifier"
1068            | "namespace_identifier"
1069            | "preproc_arg"
1070    ) || ctx.ancestry.parent(node).is_some_and(|parent| {
1071        matches!(parent.kind(), "preproc_def" | "preproc_function_def")
1072            && parent
1073                .child_by_field_name("name")
1074                .is_some_and(|name| same_node(name, node))
1075    }) {
1076        return;
1077    }
1078    if ctx.visibility.macro_binding_matches_target_declaration_at(
1079        ctx.file,
1080        &ctx.spec.member_name,
1081        node.start_byte(),
1082        ctx.spec.target.source(),
1083        &ctx.target_macro_declaration_bytes,
1084    ) {
1085        *ctx.raw_match_count += 1;
1086        push_hit(node, ctx);
1087    } else if ctx.visibility.macro_name_may_be_bound_at(
1088        ctx.file,
1089        &ctx.spec.member_name,
1090        node.start_byte(),
1091    ) && ctx
1092        .visibility
1093        .macro_target_is_visible_candidate(ctx.file, &ctx.spec.target)
1094    {
1095        *ctx.raw_match_count += 1;
1096        push_unproven_hit(node, ctx);
1097    }
1098}
1099
1100fn maybe_record_type_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1101    let kind = node.kind();
1102    if ctx.uses_c_semantics
1103        && recovered_c_new_expression_argument_at(node, node.start_byte(), node.end_byte(), true)
1104            .is_some()
1105    {
1106        return;
1107    }
1108    if kind == "preproc_arg" {
1109        maybe_record_object_macro_replacement_type_hits(node, ctx);
1110        return;
1111    }
1112    if let Some(type_node) = ctx
1113        .visibility
1114        .function_macro_type_argument(ctx.file, node, ctx.source)
1115    {
1116        if ctx
1117            .local_shadows
1118            .is_shadowed(node_text(type_node, ctx.source))
1119        {
1120            return;
1121        }
1122        if let LexicalTypeResolution::Resolved {
1123            unit, candidates, ..
1124        } = resolve_type_node_lexically_for_target(
1125            type_node,
1126            &ctx.analyzer,
1127            ctx.visibility,
1128            &ctx.ordinary_type_imports,
1129            ctx.file,
1130            ctx.source,
1131            &ctx.spec.target,
1132            Some(&ctx.lexical_scope_cache),
1133            ctx.recovered_sentinel_scope(type_node).as_deref(),
1134        ) && type_resolution_matches_target(type_node, &unit, &candidates, ctx)
1135        {
1136            *ctx.raw_match_count += 1;
1137            push_type_hit(type_node, ctx);
1138        }
1139        return;
1140    }
1141    let recovered_exported_class_base =
1142        matches!(
1143            kind,
1144            "qualified_identifier" | "scoped_type_identifier" | "template_type"
1145        ) && is_recovered_exported_class_base_type_node(node, ctx.source);
1146    if kind == "field_declaration"
1147        && let Some(return_type) = recovered_macro_return_type_node(node, ctx.source)
1148    {
1149        maybe_record_recovered_macro_return_type_hit(return_type, ctx);
1150        return;
1151    }
1152    if kind == "qualified_identifier"
1153        && let Some((owner, _member_pointer)) = member_pointer_owner_components(node, ctx.source)
1154    {
1155        // A member-pointer owner can itself end in a nested alias, as in
1156        // `type_identity<T>::type::*`. Resolving the complete owner
1157        // canonicalizes that alias to its underlying type and loses the alias
1158        // declaration that inverse lookup is targeting. Retain every
1159        // structurally proven qualifier component before asking for the
1160        // canonical owner type.
1161        if ctx
1162            .analyzer
1163            .type_alias_provider()
1164            .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
1165            && canonical_cpp_scope_components(&ctx.spec.target) == owner.names
1166            && let Some(terminal) = owner.nodes.last().copied()
1167        {
1168            if !member_pointer_alias_owner_prefix_matches(node, &owner, ctx) {
1169                return;
1170            }
1171            if ctx.visibility.external_type_candidate_visible_in_context(
1172                &ctx.analyzer,
1173                ctx.file,
1174                &ctx.spec.target,
1175                terminal,
1176            ) || ctx
1177                .visibility
1178                .dependent_member_pointer_alias_visible_in_context(
1179                    &ctx.analyzer,
1180                    ctx.file,
1181                    &ctx.spec.target,
1182                    &owner.names,
1183                    terminal,
1184                )
1185            {
1186                *ctx.raw_match_count += 1;
1187                push_type_hit(terminal, ctx);
1188            }
1189            return;
1190        }
1191        if let Some(scopes) = static_qualifier_type_scopes_for_components(node, owner, ctx) {
1192            *ctx.raw_match_count += 1;
1193            for scope in scopes {
1194                push_type_hit(scope, ctx);
1195            }
1196            return;
1197        }
1198        return;
1199    }
1200    if kind == "pointer_expression"
1201        && let Some(value) = qualified_callable_value(node)
1202        && let Some(owner_hit) = target_guided_qualified_value_owner_hit(value.qualified, ctx)
1203    {
1204        *ctx.raw_match_count += 1;
1205        match owner_hit {
1206            TargetGuidedQualifiedValueOwnerHit::Proven(scope) => push_type_hit(scope, ctx),
1207            TargetGuidedQualifiedValueOwnerHit::Unproven(scope) => push_unproven_hit(scope, ctx),
1208        }
1209        return;
1210    }
1211    if kind == "call_expression" {
1212        maybe_record_direct_temporary_type_hit(node, ctx);
1213        return;
1214    }
1215    if !matches!(
1216        kind,
1217        "identifier"
1218            | "namespace_identifier"
1219            | "qualified_identifier"
1220            | "scoped_identifier"
1221            | "scoped_type_identifier"
1222            | "template_function"
1223            | "template_type"
1224            | "type_descriptor"
1225            | "type_identifier"
1226            | "using_declaration"
1227    ) {
1228        return;
1229    }
1230    let recovered_type = recovered_macro_decorated_declarator_type(node).is_some();
1231    let template_function_type = cpp_template_function_has_type_owner(node);
1232    let recovered_qualified_friend =
1233        is_recovered_qualified_friend_class_type_reference(node, ctx.source);
1234    if !recovered_type
1235        && !recovered_qualified_friend
1236        && !recovered_exported_class_base
1237        && matches!(
1238            kind,
1239            "type_identifier" | "qualified_identifier" | "scoped_type_identifier" | "template_type"
1240        )
1241        && !type_reference_components_may_name_target(node, ctx)
1242    {
1243        return;
1244    }
1245    if ctx.ancestry.parent(node).is_some_and(|parent| {
1246        parent.kind() == "operator_cast"
1247            && parent
1248                .child_by_field_name("type")
1249                .is_some_and(|target| same_node(target, node))
1250    }) {
1251        return;
1252    }
1253    if let Some(hit) = target_guided_static_cast_alias_type_descriptor(node, ctx) {
1254        *ctx.raw_match_count += 1;
1255        push_type_hit(hit, ctx);
1256        return;
1257    }
1258    if matches!(kind, "identifier" | "template_function")
1259        && parent_if_field(node, "call_expression", "function").is_some()
1260    {
1261        return;
1262    }
1263    if kind == "using_declaration" {
1264        let (resolution, type_node) =
1265            if let Some(type_node) = using_enum_declaration_type_node(node) {
1266                (
1267                    resolve_using_enum_declaration_owner(
1268                        node,
1269                        &ctx.analyzer,
1270                        ctx.visibility,
1271                        &ctx.ordinary_type_imports,
1272                        ctx.file,
1273                        ctx.source,
1274                    ),
1275                    type_node,
1276                )
1277            } else if let Some(type_node) = ordinary_using_declaration_type_node(node) {
1278                (
1279                    resolve_ordinary_using_declaration_owner(
1280                        node,
1281                        &ctx.analyzer,
1282                        ctx.visibility,
1283                        ctx.file,
1284                        ctx.source,
1285                    ),
1286                    type_node,
1287                )
1288            } else {
1289                return;
1290            };
1291        if let LexicalTypeResolution::Resolved { unit, .. } = resolution
1292            && same_visible_symbol(&unit, &ctx.spec.target)
1293        {
1294            *ctx.raw_match_count += 1;
1295            push_type_hit(type_node, ctx);
1296        }
1297        return;
1298    }
1299    if ctx.uses_c_semantics && is_c_sizeof_expression_type_candidate(ctx.file, node) {
1300        if ctx.local_shadows.is_shadowed(node_text(node, ctx.source))
1301            || local_type_name_shadows(node, ctx)
1302        {
1303            return;
1304        }
1305        if let LexicalTypeResolution::Resolved {
1306            unit, candidates, ..
1307        } = resolve_type_node_lexically_for_target(
1308            node,
1309            &ctx.analyzer,
1310            ctx.visibility,
1311            &ctx.ordinary_type_imports,
1312            ctx.file,
1313            ctx.source,
1314            &ctx.spec.target,
1315            Some(&ctx.lexical_scope_cache),
1316            ctx.recovered_sentinel_scope(node).as_deref(),
1317        ) && type_resolution_matches_target(node, &unit, &candidates, ctx)
1318        {
1319            *ctx.raw_match_count += 1;
1320            push_type_hit(node, ctx);
1321        }
1322        return;
1323    }
1324    if let Some((type_node, _)) = recovered_macro_decorated_type_node(node) {
1325        // A missing `::` can put either the macro or the real type in the
1326        // recovered scope. Resolve both candidates against this inverse
1327        // target before choosing one: a unique match is routed through the
1328        // ordinary target-guided path, while two distinct matches are
1329        // ambiguous and must not invent a hit. With no target match, retain
1330        // the existing recovered-scope path below for its conservative
1331        // fallback behaviour.
1332        let mut matching = Vec::new();
1333        for candidate in [node, type_node] {
1334            if matching
1335                .iter()
1336                .any(|existing| same_node(*existing, candidate))
1337            {
1338                continue;
1339            }
1340            if let LexicalTypeResolution::Resolved {
1341                unit, candidates, ..
1342            } = resolve_type_node_lexically_for_target(
1343                candidate,
1344                &ctx.analyzer,
1345                ctx.visibility,
1346                &ctx.ordinary_type_imports,
1347                ctx.file,
1348                ctx.source,
1349                &ctx.spec.target,
1350                Some(&ctx.lexical_scope_cache),
1351                ctx.recovered_sentinel_scope(candidate).as_deref(),
1352            ) && type_resolution_matches_target(candidate, &unit, &candidates, ctx)
1353            {
1354                matching.push(candidate);
1355            }
1356        }
1357        match matching.as_slice() {
1358            [candidate] if !same_node(*candidate, node) => {
1359                maybe_record_type_hit(*candidate, ctx);
1360                return;
1361            }
1362            [candidate] if same_node(*candidate, node) => {}
1363            [] => {}
1364            _ => return,
1365        }
1366    }
1367    if !recovered_type
1368        && !template_function_type
1369        && !matches!(
1370            kind,
1371            "type_identifier" | "qualified_identifier" | "scoped_type_identifier" | "template_type"
1372        )
1373    {
1374        return;
1375    }
1376    if type_reference_components(node, ctx.source).is_some_and(|(components, global)| {
1377        components.len() == 1 && !global && local_type_name_shadows(node, ctx)
1378    }) {
1379        return;
1380    }
1381    if !recovered_type
1382        && !recovered_qualified_friend
1383        && !recovered_exported_class_base
1384        && ctx.ancestry.parent(node).is_some_and(|parent| {
1385            parent.kind() == "alias_declaration"
1386                && parent
1387                    .child_by_field_name("name")
1388                    .is_some_and(|name| same_node(name, node))
1389        })
1390    {
1391        return;
1392    }
1393    #[cfg(any(test, feature = "test-support"))]
1394    TYPE_REFERENCE_CANDIDATE_SCAN_COUNT.with(|count| count.set(count.get() + 1));
1395    if !recovered_type
1396        && !recovered_qualified_friend
1397        && !recovered_exported_class_base
1398        && matches!(kind, "qualified_identifier" | "scoped_identifier")
1399        && is_declaration_name(node)
1400        && let Some(owners) = out_of_line_member_definition_owner(
1401            &ctx.analyzer,
1402            ctx.visibility,
1403            ctx.file,
1404            ctx.source,
1405            node,
1406        )
1407    {
1408        *ctx.raw_match_count += 1;
1409        let mut matched_owner = false;
1410        for (owner_node, owner) in owners.owners {
1411            if same_visible_symbol(&owner, &ctx.spec.target) {
1412                matched_owner = true;
1413                push_guarded_owner_hit(owner_node, &owner, node, ctx);
1414            }
1415        }
1416        if !matched_owner && let Some(scopes) = target_guided_qualifier_type_scopes(node, ctx) {
1417            for scope in scopes {
1418                push_hit(scope, ctx);
1419            }
1420        } else if !matched_owner
1421            && let Some(scope) = target_guided_unproven_out_of_line_owner(node, ctx)
1422        {
1423            push_unproven_hit(scope, ctx);
1424        }
1425        return;
1426    }
1427    if !recovered_type
1428        && !recovered_qualified_friend
1429        && matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
1430        && is_declaration_name(node)
1431        && let Some(owner) = indexed_out_of_line_template_owner_hit(node, ctx)
1432    {
1433        *ctx.raw_match_count += 1;
1434        push_type_hit(owner, ctx);
1435        return;
1436    }
1437    // A qualified template-id is represented as a qualified_identifier whose
1438    // name child is the template_type. Resolve the complete qualified
1439    // reference from that inner template node below; handling the outer node
1440    // independently would either lose the qualifier or emit a duplicate,
1441    // wider hit range.
1442    if ctx.visibility.is_template_specialization(&ctx.spec.target)
1443        && matches!(
1444            node.kind(),
1445            "qualified_identifier" | "scoped_type_identifier"
1446        )
1447        && node
1448            .child_by_field_name("name")
1449            .is_some_and(|name| name.kind() == "template_type")
1450    {
1451        return;
1452    }
1453    if let Some(scope) = target_guided_dependent_alias_qualifier_scope(node, ctx) {
1454        *ctx.raw_match_count += 1;
1455        push_unproven_hit(scope, ctx);
1456        return;
1457    }
1458    if !recovered_type
1459        && !is_nested_type_node(node)
1460        && matches!(
1461            node.kind(),
1462            "qualified_identifier" | "scoped_type_identifier"
1463        )
1464        && let Some(scopes) = target_guided_qualifier_type_scopes(node, ctx)
1465    {
1466        *ctx.raw_match_count += 1;
1467        for scope in scopes {
1468            push_type_hit(scope, ctx);
1469        }
1470        return;
1471    }
1472    if !recovered_type && is_nested_type_node(node) {
1473        if let Some(hit) = out_of_line_dependent_return_template_owner(node, ctx) {
1474            *ctx.raw_match_count += 1;
1475            push_type_hit(hit, ctx);
1476            return;
1477        }
1478        if let Some(hit) = target_guided_nested_type_terminal_hit(node, ctx) {
1479            *ctx.raw_match_count += 1;
1480            push_type_hit(hit, ctx);
1481            return;
1482        }
1483        // A concrete template specialization can be absent from the coarse
1484        // per-file component-name index: that index contains the primary name
1485        // while this recovered child may expose only the malformed template
1486        // leaf.  Resolve the complete enclosing template before applying the
1487        // component prefilter so an exact target candidate can prove this
1488        // reference.  Non-specialization targets retain the cheap gate.
1489        let nested_template = if node.kind() == "template_type" {
1490            Some(node)
1491        } else {
1492            ctx.ancestry.parent(node).filter(|parent| {
1493                parent.kind() == "template_type" && parent.child_by_field_name("name") == Some(node)
1494            })
1495        };
1496        // Concrete specializations need their nested template-id inspected.
1497        // An ordinary alias application does too when it is itself the scope
1498        // of a member-qualified type, because the enclosing node denotes the
1499        // member rather than the alias. In every other primary/alias shape the
1500        // enclosing structured type owns the hit range; descending would emit
1501        // a duplicate terminal subrange.
1502        let nested_alias_qualifier = nested_template.is_some_and(|template| {
1503            let enclosing_qualified_type_owns_range =
1504                ctx.ancestry.parent(template).is_some_and(|parent| {
1505                    matches!(
1506                        parent.kind(),
1507                        "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
1508                    ) && parent.child_by_field_name("name") == Some(template)
1509                });
1510            let Some(alias_provider) = ctx.analyzer.type_alias_provider() else {
1511                return false;
1512            };
1513            let Some(name) = template_reference_name_node(template) else {
1514                return false;
1515            };
1516            let alias_candidates = ctx
1517                .visibility
1518                .visible_identifier_candidates(ctx.file, node_text(name, ctx.source))
1519                .filter(|candidate| alias_provider.is_type_alias(candidate))
1520                .cloned()
1521                .collect::<Vec<_>>();
1522            let direct_target_alias_visible = !alias_candidates
1523                .iter()
1524                .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
1525                || ctx.visibility.external_type_candidate_visible_in_context(
1526                    &ctx.analyzer,
1527                    ctx.file,
1528                    &ctx.spec.target,
1529                    template,
1530                );
1531            !enclosing_qualified_type_owns_range
1532                && direct_target_alias_visible
1533                && template_reference_candidates_select_target(
1534                    template,
1535                    &alias_candidates,
1536                    &ctx.analyzer,
1537                    ctx.visibility,
1538                    ctx.file,
1539                    ctx.source,
1540                    &ctx.spec.target,
1541                )
1542        });
1543        if !ctx.visibility.is_template_specialization(&ctx.spec.target) && !nested_alias_qualifier {
1544            return;
1545        }
1546        if nested_alias_qualifier {
1547            let template = nested_template.expect("a nested alias qualifier has a template node");
1548            *ctx.raw_match_count += 1;
1549            let hit = target_guided_missing_alias_rhs_type_leaf(template, ctx)
1550                .unwrap_or_else(|| type_reference_hit_node(template));
1551            push_type_hit(hit, ctx);
1552            return;
1553        }
1554        // For concrete specializations, the visible identifier index can
1555        // already contain the exact template spelling even when lexical
1556        // resolution rejects the recovered child (the child itself has no
1557        // argument list). Select the name as structured evidence;
1558        // `push_type_hit` expands it to the complete written template-id.
1559        if ctx.visibility.is_template_specialization(&ctx.spec.target)
1560            && let Some(template) = nested_template
1561            && template_type_component_preserves_target(
1562                template,
1563                &ctx.visibility
1564                    .visible_identifier_candidates(ctx.file, node_text(template, ctx.source))
1565                    .cloned()
1566                    .collect::<Vec<_>>(),
1567                ctx,
1568            )
1569        {
1570            *ctx.raw_match_count += 1;
1571            let hit = template
1572                .child_by_field_name("name")
1573                .filter(|name| name.kind() == "type_identifier")
1574                .unwrap_or(template);
1575            push_type_hit(hit, ctx);
1576            return;
1577        }
1578        if let Some(template) = nested_template
1579            && let Some(_resolution) = resolve_nested_template_type_for_target(template, ctx)
1580        {
1581            *ctx.raw_match_count += 1;
1582            let hit =
1583                target_guided_missing_alias_rhs_type_leaf(template, ctx).unwrap_or_else(|| {
1584                    if ctx.visibility.is_template_specialization(&ctx.spec.target) {
1585                        template
1586                            .child_by_field_name("name")
1587                            .filter(|name| name.kind() == "type_identifier")
1588                            .unwrap_or(template)
1589                    } else {
1590                        type_reference_hit_node(template)
1591                    }
1592                });
1593            push_type_hit(hit, ctx);
1594        }
1595        return;
1596    }
1597    if !recovered_type && let Some(call) = parent_if_field(node, "call_expression", "function") {
1598        let direct_target = resolve_qualified_call_target(
1599            call,
1600            node,
1601            &ctx.analyzer,
1602            ctx.visibility,
1603            &ctx.ordinary_type_imports,
1604            ctx.file,
1605            ctx.source,
1606        );
1607        if matches!(direct_target, BareCallTargetResolution::Type(_))
1608            && let LexicalTypeResolution::Resolved {
1609                unit, candidates, ..
1610            } = resolve_type_node_lexically_for_target(
1611                node,
1612                &ctx.analyzer,
1613                ctx.visibility,
1614                &ctx.ordinary_type_imports,
1615                ctx.file,
1616                ctx.source,
1617                &ctx.spec.target,
1618                Some(&ctx.lexical_scope_cache),
1619                ctx.recovered_sentinel_scope(node).as_deref(),
1620            )
1621            && type_resolution_matches_target(node, &unit, &candidates, ctx)
1622        {
1623            *ctx.raw_match_count += 1;
1624            push_resolved_type_hit(node, &candidates, ctx);
1625        } else if let Some(scopes) = static_qualifier_type_scopes(node, ctx) {
1626            *ctx.raw_match_count += 1;
1627            for scope in scopes {
1628                push_type_hit(scope, ctx);
1629            }
1630        } else if let Some(owner_hit) = target_guided_qualified_value_owner_hit(node, ctx) {
1631            *ctx.raw_match_count += 1;
1632            match owner_hit {
1633                TargetGuidedQualifiedValueOwnerHit::Proven(scope) => push_type_hit(scope, ctx),
1634                TargetGuidedQualifiedValueOwnerHit::Unproven(scope) => {
1635                    push_unproven_hit(scope, ctx)
1636                }
1637            }
1638        }
1639        return;
1640    }
1641    if let Some((hit, proven)) = target_guided_alias_template_reference(node, ctx) {
1642        *ctx.raw_match_count += 1;
1643        if proven {
1644            push_type_hit(hit, ctx);
1645        } else {
1646            push_unproven_hit(hit, ctx);
1647        }
1648        return;
1649    }
1650    if !recovered_type
1651        && !recovered_qualified_friend
1652        && !recovered_exported_class_base
1653        && is_declaration_name(node)
1654    {
1655        let mut matched_owner = false;
1656        if let Some(owners) = out_of_line_member_definition_owner(
1657            &ctx.analyzer,
1658            ctx.visibility,
1659            ctx.file,
1660            ctx.source,
1661            node,
1662        ) {
1663            for (owner_node, owner) in owners.owners {
1664                if same_visible_symbol(&owner, &ctx.spec.target) {
1665                    matched_owner = true;
1666                    *ctx.raw_match_count += 1;
1667                    push_guarded_owner_hit(owner_node, &owner, node, ctx);
1668                }
1669            }
1670        }
1671        if !matched_owner && let Some(scopes) = target_guided_qualifier_type_scopes(node, ctx) {
1672            *ctx.raw_match_count += 1;
1673            for scope in scopes {
1674                push_hit(scope, ctx);
1675            }
1676        } else if !matched_owner
1677            && let Some(scope) = target_guided_unproven_out_of_line_owner(node, ctx)
1678        {
1679            *ctx.raw_match_count += 1;
1680            push_unproven_hit(scope, ctx);
1681        }
1682        return;
1683    }
1684    let hit_node = node;
1685    let text = node_text(hit_node, ctx.source);
1686    let type_resolution = if hit_node.kind() == "template_type"
1687        && ctx.visibility.is_template_specialization(&ctx.spec.target)
1688    {
1689        resolve_nested_template_type_for_target(hit_node, ctx).unwrap_or_else(|| {
1690            resolve_type_node_lexically_for_target(
1691                hit_node,
1692                &ctx.analyzer,
1693                ctx.visibility,
1694                &ctx.ordinary_type_imports,
1695                ctx.file,
1696                ctx.source,
1697                &ctx.spec.target,
1698                Some(&ctx.lexical_scope_cache),
1699                ctx.recovered_sentinel_scope(hit_node).as_deref(),
1700            )
1701        })
1702    } else {
1703        resolve_type_node_lexically_for_target(
1704            hit_node,
1705            &ctx.analyzer,
1706            ctx.visibility,
1707            &ctx.ordinary_type_imports,
1708            ctx.file,
1709            ctx.source,
1710            &ctx.spec.target,
1711            Some(&ctx.lexical_scope_cache),
1712            ctx.recovered_sentinel_scope(hit_node).as_deref(),
1713        )
1714    };
1715    match type_resolution {
1716        LexicalTypeResolution::Resolved {
1717            unit, candidates, ..
1718        } if type_resolution_matches_target(node, &unit, &candidates, ctx) => {
1719            *ctx.raw_match_count += 1;
1720            if let Some(scopes) = static_qualifier_type_scopes(node, ctx) {
1721                for scope in scopes {
1722                    push_type_hit(scope, ctx);
1723                }
1724            } else {
1725                push_resolved_type_hit(hit_node, &candidates, ctx);
1726            }
1727            return;
1728        }
1729        LexicalTypeResolution::Resolved {
1730            unit: _,
1731            candidates,
1732            ..
1733        } => {
1734            if let Some(scopes) = static_qualifier_type_scopes(node, ctx) {
1735                *ctx.raw_match_count += 1;
1736                for scope in scopes {
1737                    push_type_hit(scope, ctx);
1738                }
1739            } else if let Some(hit) =
1740                target_guided_unproven_alias_type_reference(node, &candidates, ctx)
1741            {
1742                *ctx.raw_match_count += 1;
1743                push_unproven_hit(hit, ctx);
1744            } else if let Some(leaf) = target_guided_missing_alias_rhs_type_leaf(node, ctx)
1745                .or_else(|| target_guided_missing_member_alias_type_leaf(node, ctx))
1746            {
1747                *ctx.raw_match_count += 1;
1748                push_type_hit(leaf, ctx);
1749            } else if let Some(leaf) = target_guided_dependent_class_alias_leaf(node, ctx) {
1750                *ctx.raw_match_count += 1;
1751                push_unproven_hit(leaf, ctx);
1752            }
1753            return;
1754        }
1755        LexicalTypeResolution::Ambiguous => {
1756            if let Some(scopes) = static_qualifier_type_scopes(node, ctx) {
1757                *ctx.raw_match_count += 1;
1758                for scope in scopes {
1759                    push_type_hit(scope, ctx);
1760                }
1761            } else if let Some(leaf) = target_guided_dependent_class_alias_leaf(node, ctx) {
1762                *ctx.raw_match_count += 1;
1763                push_unproven_hit(leaf, ctx);
1764            } else if let Some(leaf) = target_guided_missing_alias_rhs_type_leaf(node, ctx)
1765                .or_else(|| target_guided_missing_member_alias_type_leaf(node, ctx))
1766                .or_else(|| target_guided_ambiguous_owned_alias_type_leaf(node, ctx))
1767            {
1768                *ctx.raw_match_count += 1;
1769                push_type_hit(leaf, ctx);
1770            }
1771            return;
1772        }
1773        LexicalTypeResolution::Missing => {
1774            if let Some(unit) = ctx.visibility.unique_visible_parameter_type_fallback(
1775                &ctx.analyzer,
1776                ctx.file,
1777                hit_node,
1778                ctx.source,
1779            ) && same_visible_symbol(&unit, &ctx.spec.target)
1780            {
1781                *ctx.raw_match_count += 1;
1782                push_type_hit(hit_node, ctx);
1783                return;
1784            }
1785            if let Some(leaf) = target_guided_compatible_foreign_import_type_leaf(node, ctx) {
1786                *ctx.raw_match_count += 1;
1787                push_unproven_hit(leaf, ctx);
1788                return;
1789            }
1790            if let Some(leaf) = target_guided_dependent_class_alias_leaf(node, ctx) {
1791                *ctx.raw_match_count += 1;
1792                push_unproven_hit(leaf, ctx);
1793                return;
1794            }
1795            if let Some(leaf) = target_guided_missing_type_leaf(node, ctx) {
1796                *ctx.raw_match_count += 1;
1797                push_type_hit(leaf, ctx);
1798                return;
1799            }
1800            let raw_resolution = resolve_type_node_lexically_for_target_without_visibility(
1801                hit_node,
1802                &ctx.analyzer,
1803                ctx.visibility,
1804                ctx.file,
1805                ctx.source,
1806                &ctx.spec.target,
1807            );
1808            let raw_matches = matches!(
1809                raw_resolution,
1810                LexicalTypeResolution::Resolved {
1811                    ref unit,
1812                    ref candidates,
1813                    ..
1814                } if type_resolution_identifies_unit_target(
1815                    hit_node,
1816                    unit,
1817                    candidates,
1818                    &ctx.spec.target,
1819                    ctx,
1820                )
1821            );
1822            if raw_matches
1823                || type_node_has_exact_target_identity_without_visibility(
1824                    hit_node,
1825                    &ctx.analyzer,
1826                    ctx.visibility,
1827                    ctx.file,
1828                    ctx.source,
1829                    &ctx.spec.target,
1830                )
1831            {
1832                *ctx.raw_match_count += 1;
1833                push_unproven_hit(type_reference_hit_node(hit_node), ctx);
1834                return;
1835            }
1836        }
1837    }
1838    // A class-owned alias can be qualified by an owner made visible through a
1839    // namespace import, including an import in an earlier reopening of the
1840    // same unnamed namespace. Resolve that owner before requiring an
1841    // enclosing class for inherited nested-type lookup.
1842    if ctx
1843        .visibility
1844        .parser_alias_resolves_to_type(ctx.file, text, &ctx.spec.target)
1845    {
1846        *ctx.raw_match_count += 1;
1847        push_type_hit(type_reference_hit_node(hit_node), ctx);
1848        return;
1849    }
1850    if let Some(scopes) = static_qualifier_type_scopes(node, ctx) {
1851        *ctx.raw_match_count += 1;
1852        for scope in scopes {
1853            push_type_hit(scope, ctx);
1854        }
1855        return;
1856    }
1857    if !name_mentions(text, &ctx.spec.member_name) {
1858        return;
1859    }
1860    *ctx.raw_match_count += 1;
1861    if !ctx.visibility.external_type_candidate_visible_in_context(
1862        &ctx.analyzer,
1863        ctx.file,
1864        &ctx.spec.target,
1865        hit_node,
1866    ) {
1867        let unproven = static_qualifier_name_scope(node, ctx).unwrap_or(hit_node);
1868        if type_reference_resolves_away_from_target(unproven, ctx) {
1869            return;
1870        }
1871        push_unproven_hit(unproven, ctx);
1872    }
1873}
1874
1875fn maybe_record_object_macro_replacement_type_hits(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
1876    for reference in object_macro_replacement_type_references(node, ctx.source) {
1877        for component_count in 1..=reference.components.len() {
1878            let resolution = resolve_type_components_lexically_at_for_target_with_scope_cache(
1879                node,
1880                &reference.components[..component_count],
1881                reference.global,
1882                &ctx.analyzer,
1883                ctx.visibility,
1884                &ctx.ordinary_type_imports,
1885                ctx.file,
1886                ctx.source,
1887                &ctx.spec.target,
1888                false,
1889                Some(&ctx.lexical_scope_cache),
1890            );
1891            let matches_target = match resolution {
1892                LexicalTypeResolution::Resolved {
1893                    unit, candidates, ..
1894                } => {
1895                    same_visible_symbol(&unit, &ctx.spec.target)
1896                        || candidates
1897                            .iter()
1898                            .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
1899                }
1900                LexicalTypeResolution::Missing => unique_macro_replacement_type_candidate(
1901                    &ctx.analyzer,
1902                    ctx.visibility,
1903                    ctx.file,
1904                    &reference.components[..component_count],
1905                )
1906                .is_some_and(|candidate| same_visible_symbol(&candidate, &ctx.spec.target)),
1907                LexicalTypeResolution::Ambiguous => false,
1908            };
1909            if !matches_target {
1910                continue;
1911            }
1912            let range = &reference.component_ranges[component_count - 1];
1913            *ctx.raw_match_count += 1;
1914            push_type_hit_range(node, range.start, range.end, ctx);
1915        }
1916    }
1917}
1918
1919fn target_guided_compatible_foreign_import_type_leaf<'tree>(
1920    node: Node<'tree>,
1921    ctx: &ScanCtx<'_>,
1922) -> Option<Node<'tree>> {
1923    let (components, global) = type_reference_components(node, ctx.source)?;
1924    let lexical_scope = ctx.recovered_sentinel_scope(node).or_else(|| {
1925        match cached_enclosing_lexical_scope_components_with_unresolved_owner(
1926            node,
1927            &ctx.analyzer,
1928            ctx.visibility,
1929            ctx.file,
1930            ctx.source,
1931            false,
1932            false,
1933            Some(&ctx.lexical_scope_cache),
1934        ) {
1935            LexicalScopeResolution::Resolved(scope) => Some(scope),
1936            LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => None,
1937        }
1938    })?;
1939    let OrdinaryTypeImportResolution::Resolved { target, .. } =
1940        compatible_foreign_type_import_resolution(
1941            node,
1942            &components,
1943            global,
1944            &ctx.analyzer,
1945            ctx.visibility,
1946            &ctx.ordinary_type_imports,
1947            ctx.file,
1948            ctx.source,
1949            &lexical_scope,
1950            Some(&ctx.spec.target),
1951        )
1952    else {
1953        return None;
1954    };
1955    same_visible_symbol(&target, &ctx.spec.target).then(|| type_reference_hit_node(node))
1956}
1957
1958/// Resolve `Owner::Nested` when complete type lookup cannot express the owner
1959/// as its first qualified component. This occurs when a using-directive
1960/// imports `Owner` and when inherited-type lookup injects it. Resolve the
1961/// owner prefix independently, then return the terminal node after that owner
1962/// proves the target's direct nested declaration; hit insertion expands it to
1963/// the complete written type.
1964fn target_guided_nested_type_terminal_hit<'tree>(
1965    node: Node<'tree>,
1966    ctx: &ScanCtx<'_>,
1967) -> Option<Node<'tree>> {
1968    // Returns a node of the caller's tree lifetime, which the context-scoped
1969    // ancestry index cannot name; this is one question per call.
1970    let qualified = node.parent().filter(|parent| {
1971        matches!(
1972            parent.kind(),
1973            "qualified_identifier" | "scoped_type_identifier"
1974        ) && parent.child_by_field_name("name") == Some(node)
1975    })?;
1976    let mut complete = qualified;
1977    while let Some(parent) = complete.parent().filter(|parent| {
1978        matches!(
1979            parent.kind(),
1980            "qualified_identifier" | "scoped_type_identifier"
1981        )
1982    }) {
1983        complete = parent;
1984    }
1985    let owner = qualified_owner_components(complete, ctx.source)?;
1986
1987    if let LexicalTypeResolution::Resolved {
1988        unit, candidates, ..
1989    } = resolve_type_node_lexically_for_target(
1990        complete,
1991        &ctx.analyzer,
1992        ctx.visibility,
1993        &ctx.ordinary_type_imports,
1994        ctx.file,
1995        ctx.source,
1996        &ctx.spec.target,
1997        Some(&ctx.lexical_scope_cache),
1998        ctx.recovered_sentinel_scope(complete).as_deref(),
1999    ) && type_resolution_matches_target(complete, &unit, &candidates, ctx)
2000        && ctx
2001            .analyzer
2002            .parent_of(&ctx.spec.target)
2003            .is_some_and(|parent| parent.is_class())
2004        && !ctx
2005            .analyzer
2006            .type_alias_provider()
2007            .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
2008        && is_namespace_scope_type_reference(complete)
2009        && namespace_import_can_name_nested_target(complete, ctx)
2010    {
2011        return Some(node);
2012    }
2013
2014    let target_owner = ctx
2015        .analyzer
2016        .parent_of(&ctx.spec.target)
2017        .filter(CodeUnit::is_class);
2018    let owner_spelling_can_name_target = target_owner.as_ref().is_some_and(|target_owner| {
2019        let target_components = canonical_cpp_scope_components(target_owner);
2020        if owner.global {
2021            target_components == owner.names
2022        } else {
2023            target_components.ends_with(&owner.names)
2024        }
2025    });
2026    let target_member_visible = |target_owner: &CodeUnit| {
2027        ctx.visibility
2028            .visible_members_for_owner_name(ctx.file, target_owner, node_text(node, ctx.source))
2029            .into_iter()
2030            .any(|candidate| {
2031                same_visible_symbol(candidate, &ctx.spec.target)
2032                    && (ctx
2033                        .visibility
2034                        .external_type_candidate_guard_compatible_in_context(
2035                            &ctx.analyzer,
2036                            ctx.file,
2037                            candidate,
2038                            complete,
2039                        )
2040                        || (ctx
2041                            .visibility
2042                            .is_exhaustive_same_fqn_type_declaration_family(
2043                                &ctx.analyzer,
2044                                ctx.file,
2045                                candidate,
2046                            )
2047                            && ctx.visibility.external_type_candidate_visible_in_context(
2048                                &ctx.analyzer,
2049                                ctx.file,
2050                                candidate,
2051                                complete,
2052                            )))
2053            })
2054    };
2055
2056    if owner_spelling_can_name_target
2057        && (is_namespace_scope_type_reference(complete)
2058            || (is_compound_type_reference(complete)
2059                && namespace_import_can_name_nested_target(complete, ctx)))
2060        && let Some(target_owner) = target_owner.as_ref()
2061        && let LexicalTypeResolution::Resolved { unit, .. } =
2062            resolve_type_components_lexically_at_preserving_alias_with_scope_cache(
2063                complete,
2064                &owner.names,
2065                owner.global,
2066                &ctx.analyzer,
2067                ctx.visibility,
2068                &ctx.ordinary_type_imports,
2069                ctx.file,
2070                ctx.source,
2071                Some(&ctx.lexical_scope_cache),
2072            )
2073        && ctx
2074            .visibility
2075            .same_template_owner_identity(&unit, target_owner)
2076        && target_member_visible(target_owner)
2077    {
2078        return Some(node);
2079    }
2080
2081    if ctx
2082        .analyzer
2083        .type_alias_provider()
2084        .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
2085        && !ctx
2086            .analyzer
2087            .parent_of(&ctx.spec.target)
2088            .is_some_and(|owner| owner.is_class())
2089        && let Some(target_owner) = target_owner.as_ref()
2090        && let LexicalTypeResolution::Resolved {
2091            unit, candidates, ..
2092        } = resolve_type_components_lexically_at_for_target_with_scope_cache(
2093            complete,
2094            &owner.names,
2095            owner.global,
2096            &ctx.analyzer,
2097            ctx.visibility,
2098            &ctx.ordinary_type_imports,
2099            ctx.file,
2100            ctx.source,
2101            target_owner,
2102            false,
2103            Some(&ctx.lexical_scope_cache),
2104        )
2105        && (ctx
2106            .visibility
2107            .same_template_owner_identity(&unit, target_owner)
2108            || candidates.iter().any(|candidate| {
2109                ctx.visibility
2110                    .same_template_owner_identity(candidate, target_owner)
2111            }))
2112        && target_member_visible(target_owner)
2113    {
2114        return Some(node);
2115    }
2116
2117    let enclosing_owner = structured_enclosing_owner(node, ctx)?;
2118    let lexical_scope = canonical_cpp_scope_components(&enclosing_owner);
2119    let owner_resolution = ctx.visibility.resolve_type_components_lexically(
2120        &ctx.analyzer,
2121        ctx.file,
2122        &owner.names,
2123        owner.global,
2124        &lexical_scope,
2125    );
2126    let owner_unit = match owner_resolution {
2127        LexicalTypeResolution::Resolved { unit, .. } => unit,
2128        LexicalTypeResolution::Missing if !owner.global && owner.names.len() == 1 => {
2129            ctx.visibility.inherited_injected_class_owner(
2130                &ctx.analyzer,
2131                ctx.file,
2132                &enclosing_owner,
2133                owner.names.first()?,
2134            )?
2135        }
2136        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => return None,
2137    };
2138    let name = node_text(node, ctx.source);
2139    ctx.visibility
2140        .visible_members_for_owner_name(ctx.file, &owner_unit, name)
2141        .into_iter()
2142        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
2143        .then_some(complete)
2144}
2145
2146fn is_namespace_scope_type_reference(node: Node<'_>) -> bool {
2147    // Namespace-scope nested classes need a terminal edge when the complete
2148    // qualified node is the only structured evidence (as in #2213). In
2149    // parameters, fields, and callable bodies the enclosing type node already
2150    // owns the exact range; adding its terminal would duplicate that edge.
2151    let mut current = node.parent();
2152    while let Some(parent) = current {
2153        match parent.kind() {
2154            "call_expression" | "new_expression" => return true,
2155            "parameter_declaration"
2156            | "optional_parameter_declaration"
2157            | "field_declaration"
2158            | "function_definition"
2159            | "function_declarator"
2160            | "class_specifier"
2161            | "struct_specifier"
2162            | "union_specifier"
2163            | "compound_statement" => return false,
2164            "declaration" => {
2165                let mut cursor = parent.walk();
2166                if parent
2167                    .named_children(&mut cursor)
2168                    .any(|child| child.kind() == "function_declarator")
2169                {
2170                    return false;
2171                }
2172            }
2173            _ => {}
2174        }
2175        current = parent.parent();
2176    }
2177    true
2178}
2179
2180fn is_compound_type_reference(node: Node<'_>) -> bool {
2181    let mut current = node.parent();
2182    while let Some(parent) = current {
2183        match parent.kind() {
2184            "compound_statement" => return true,
2185            "namespace_definition" | "translation_unit" => return false,
2186            _ => current = parent.parent(),
2187        }
2188    }
2189    false
2190}
2191
2192fn namespace_import_can_name_nested_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
2193    let Some(target_owner) = ctx.analyzer.parent_of(&ctx.spec.target) else {
2194        return false;
2195    };
2196    effective_using_bindings_for_name(
2197        ctx.visibility,
2198        &ctx.ordinary_type_imports,
2199        ctx.file,
2200        node,
2201        ctx.source,
2202        target_owner.identifier(),
2203    )
2204    .iter()
2205    .any(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
2206}
2207
2208/// Recover the class-template qualifier in a dependent leading return type of
2209/// an out-of-line member definition.
2210///
2211/// `typename Owner<T>::Alias Owner<T>::method()` contains two references to
2212/// `Owner`: one in the return type and one in the callable declarator. The
2213/// latter already has authoritative indexed owner resolution. Reuse that
2214/// structured owner evidence for the former when both template names agree;
2215/// resolving `Owner<T>::Alias` as one type would instead select terminal
2216/// `Alias` and discard the qualifier.
2217fn out_of_line_dependent_return_template_owner<'tree>(
2218    node: Node<'tree>,
2219    ctx: &ScanCtx<'_>,
2220) -> Option<Node<'tree>> {
2221    if node.kind() != "template_type" {
2222        return None;
2223    }
2224    let template_name = template_reference_name_node(node)?;
2225    let mut scope = node;
2226    while let Some(parent) = ctx.ancestry.parent(scope).filter(|parent| {
2227        matches!(
2228            parent.kind(),
2229            "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
2230        ) && parent.child_by_field_name("name") == Some(scope)
2231    }) {
2232        scope = parent;
2233    }
2234    let qualified = ctx.ancestry.parent(scope).filter(|parent| {
2235        matches!(
2236            parent.kind(),
2237            "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
2238        ) && parent.child_by_field_name("scope") == Some(scope)
2239    })?;
2240    let mut function = ctx.ancestry.parent(qualified);
2241    let function = loop {
2242        let candidate = function?;
2243        if candidate.kind() == "function_definition" {
2244            break candidate;
2245        }
2246        function = ctx.ancestry.parent(candidate);
2247    };
2248    let return_type = function.child_by_field_name("type")?;
2249    if return_type.start_byte() > node.start_byte() || node.end_byte() > return_type.end_byte() {
2250        return None;
2251    }
2252    let declarator_name = function
2253        .child_by_field_name("declarator")
2254        .and_then(declarator_name_node)?;
2255    if node_text(template_name, ctx.source) != ctx.spec.target.identifier() {
2256        return None;
2257    }
2258    let resolved_owner_matches = out_of_line_member_definition_owner(
2259        &ctx.analyzer,
2260        ctx.visibility,
2261        ctx.file,
2262        ctx.source,
2263        declarator_name,
2264    )
2265    .is_some_and(|owners| {
2266        owners
2267            .owners
2268            .iter()
2269            .any(|(_, owner)| same_logical_symbol(owner, &ctx.spec.target))
2270    });
2271    let indexed_owner_matches =
2272        indexed_out_of_line_template_owner_hit(declarator_name, ctx).is_some();
2273    let target_guided_owner_matches =
2274        target_guided_qualifier_type_scopes(declarator_name, ctx).is_some();
2275    (resolved_owner_matches || indexed_owner_matches || target_guided_owner_matches)
2276        .then_some(template_name)
2277}
2278
2279/// Use the indexed callable identity when a malformed namespace sentinel
2280/// prevents lexical lookup of an out-of-line template owner.
2281fn indexed_out_of_line_template_owner_hit<'tree>(
2282    node: Node<'tree>,
2283    ctx: &ScanCtx<'_>,
2284) -> Option<Node<'tree>> {
2285    if !matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
2286        || !is_declaration_name(node)
2287    {
2288        return None;
2289    }
2290    let mut function = ctx.ancestry.parent(node);
2291    let function = loop {
2292        let candidate = function?;
2293        if candidate.kind() == "function_definition" {
2294            break candidate;
2295        }
2296        function = ctx.ancestry.parent(candidate);
2297    };
2298    if function
2299        .child_by_field_name("declarator")
2300        .and_then(declarator_name_node)
2301        != Some(node)
2302    {
2303        return None;
2304    }
2305    let target = physically_visible_type_target(ctx)?;
2306    let qualified = qualified_owner_components(node, ctx.source)?;
2307    if qualified.names.last().map(String::as_str) != Some(target.identifier()) {
2308        return None;
2309    }
2310    if indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)?
2311        != canonical_cpp_scope_components(target)
2312    {
2313        return None;
2314    }
2315    let owner = qualified.nodes.last().copied()?;
2316    let template = if owner.kind() == "template_type" {
2317        owner
2318    } else {
2319        owner
2320            .parent()
2321            .filter(|parent| parent.kind() == "template_type")?
2322    };
2323    template_reference_name_node(template)
2324}
2325
2326fn push_guarded_owner_hit(
2327    owner_node: Node<'_>,
2328    owner: &CodeUnit,
2329    reference: Node<'_>,
2330    ctx: &mut ScanCtx<'_>,
2331) {
2332    if ctx
2333        .visibility
2334        .external_type_candidate_guard_compatible_in_context(
2335            &ctx.analyzer,
2336            ctx.file,
2337            owner,
2338            reference,
2339        )
2340    {
2341        push_hit(owner_node, ctx);
2342    } else {
2343        push_unproven_hit(owner_node, ctx);
2344    }
2345}
2346
2347/// Preserve a direct template-alias reference when a macro namespace sentinel
2348/// makes tree-sitter drop the first source path component.
2349fn target_guided_alias_template_reference<'tree>(
2350    node: Node<'tree>,
2351    ctx: &ScanCtx<'_>,
2352) -> Option<(Node<'tree>, bool)> {
2353    let alias_provider = ctx.analyzer.type_alias_provider()?;
2354    if !matches!(
2355        node.kind(),
2356        "qualified_identifier" | "scoped_type_identifier"
2357    ) || !alias_provider.is_type_alias(&ctx.spec.target)
2358    {
2359        return None;
2360    }
2361    cpp_template_reference_arguments(node, ctx.source)?;
2362    let (components, global) = type_reference_components(node, ctx.source)?;
2363    if components.last().map(String::as_str) != Some(ctx.spec.target.identifier()) {
2364        return None;
2365    }
2366    let target = physically_visible_type_target(ctx)?;
2367    let target_components = canonical_cpp_scope_components(target);
2368    let parser_namespace = enclosing_namespace_components(node, ctx.source);
2369    let path_matches = if global {
2370        components == target_components
2371            || (!parser_namespace.is_empty()
2372                && target_components.starts_with(&parser_namespace)
2373                && target_components[parser_namespace.len()..] == components)
2374    } else {
2375        let lexical_scope = match enclosing_lexical_scope_components(
2376            node,
2377            &ctx.analyzer,
2378            ctx.visibility,
2379            ctx.file,
2380            ctx.source,
2381        ) {
2382            LexicalScopeResolution::Resolved(scope) => scope,
2383            LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => parser_namespace,
2384        };
2385        lexical_component_tiers(&components, false, &lexical_scope)
2386            .any(|scope| scope == target_components)
2387    };
2388    let scoped_candidates = ctx
2389        .visibility
2390        .visible_identifier_candidates(ctx.file, target.identifier())
2391        .filter(|candidate| canonical_cpp_scope_components(candidate) == target_components)
2392        .collect::<Vec<_>>();
2393    if !path_matches
2394        || scoped_candidates.is_empty()
2395        || scoped_candidates
2396            .iter()
2397            .any(|candidate| !same_visible_symbol(candidate, target))
2398        || !ctx.visibility.structured_alias_primary_preserves_target(
2399            &ctx.analyzer,
2400            ctx.file,
2401            target,
2402            target,
2403        )
2404    {
2405        return None;
2406    }
2407    let proven = ctx.visibility.external_type_candidate_visible_in_context(
2408        &ctx.analyzer,
2409        ctx.file,
2410        target,
2411        node,
2412    );
2413    Some((node, proven))
2414}
2415
2416/// Tree-sitter can split a macro-qualified member return type into a phantom
2417/// field followed by the real function definition.  The declaration visitor
2418/// discards that phantom field, but its declarator token remains a semantic
2419/// type reference. Resolve it from the recovered or indexed class scope so an
2420/// enclosing-class alias remains distinguishable from same-spelled siblings.
2421fn maybe_record_recovered_macro_return_type_hit(return_type: Node<'_>, ctx: &mut ScanCtx<'_>) {
2422    let name = node_text(return_type, ctx.source);
2423    if name != ctx.spec.target.identifier() || ctx.local_shadows.is_shadowed(name) {
2424        return;
2425    }
2426    if physically_visible_type_target(ctx).is_some()
2427        && type_alias_owner_encloses_structured_reference(return_type, ctx)
2428        && !nearer_type_name_shadows_structured_reference(return_type, ctx)
2429        && ctx.visibility.external_type_candidate_visible_in_context(
2430            &ctx.analyzer,
2431            ctx.file,
2432            &ctx.spec.target,
2433            return_type,
2434        )
2435    {
2436        *ctx.raw_match_count += 1;
2437        push_type_hit(return_type, ctx);
2438        return;
2439    }
2440    let Some(scope) = ctx
2441        .recovered_sentinel_scope(return_type)
2442        .or_else(|| indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, return_type))
2443    else {
2444        return;
2445    };
2446    let components = [name.to_string()];
2447    let resolution = ctx.visibility.resolve_type_components_lexically(
2448        &ctx.analyzer,
2449        ctx.file,
2450        &components,
2451        false,
2452        &scope,
2453    );
2454    if let LexicalTypeResolution::Resolved {
2455        unit, candidates, ..
2456    } = resolution
2457        && (same_visible_symbol(&unit, &ctx.spec.target)
2458            || candidates
2459                .iter()
2460                .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target)))
2461    {
2462        *ctx.raw_match_count += 1;
2463        push_type_hit(return_type, ctx);
2464    }
2465}
2466
2467/// Return the class/struct scope in a C++ pointer-to-member declarator such as
2468/// `double Owner::*member`. Tree-sitter represents the owner as the `scope` of
2469/// a `qualified_identifier`, while the `name` is a pointer declarator rather
2470/// than a type node; ordinary type-reference traversal therefore skips it.
2471fn member_pointer_owner_components<'tree>(
2472    node: Node<'tree>,
2473    source: &str,
2474) -> Option<(QualifiedOwnerComponents<'tree>, Node<'tree>)> {
2475    if node.kind() != "qualified_identifier" {
2476        return None;
2477    }
2478    let declarator = node.child_by_field_name("name")?;
2479    if !matches!(
2480        declarator.kind(),
2481        "pointer_type_declarator" | "abstract_pointer_declarator"
2482    ) {
2483        return None;
2484    }
2485    let scope = node.child_by_field_name("scope")?;
2486    // Keep this check entirely structural.  C and C++ share the
2487    // `qualified_identifier` node shape for some recovered declarations, but
2488    // only the C++ member-pointer form has an actual `::` grammar child
2489    // between the owner scope and pointer declarator.  Looking at the source
2490    // slice here would make a recovered C declarator look like a C++ owner
2491    // merely because its bytes happen to contain the same punctuation.
2492    let mut saw_scope = false;
2493    let has_scope_separator = (0..node.child_count()).any(|index| {
2494        let Some(child) = node.child(index) else {
2495            return false;
2496        };
2497        if same_node(child, scope) {
2498            saw_scope = true;
2499            return false;
2500        }
2501        saw_scope && !same_node(child, declarator) && child.kind() == "::" && !child.is_missing()
2502    });
2503    if !has_scope_separator {
2504        return None;
2505    }
2506    let mut nodes = cpp_name_component_nodes(scope)?;
2507    let mut outer = node;
2508    while let Some(parent) = outer.parent()
2509        && parent.kind() == "qualified_identifier"
2510        && parent.child_by_field_name("name") == Some(outer)
2511    {
2512        let mut prefix = cpp_name_component_nodes(parent.child_by_field_name("scope")?)?;
2513        prefix.append(&mut nodes);
2514        nodes = prefix;
2515        outer = parent;
2516    }
2517    let names = nodes
2518        .iter()
2519        .map(|component| node_text(*component, source).to_string())
2520        .collect();
2521    Some((
2522        QualifiedOwnerComponents {
2523            nodes,
2524            names,
2525            global: is_globally_qualified_cpp_name(outer),
2526        },
2527        outer,
2528    ))
2529}
2530
2531fn member_pointer_alias_owner_prefix_matches(
2532    node: Node<'_>,
2533    owner: &QualifiedOwnerComponents<'_>,
2534    ctx: &ScanCtx<'_>,
2535) -> bool {
2536    let Some((_, owner_prefix)) = owner.names.split_last() else {
2537        return false;
2538    };
2539    let Some(parent) = type_owner_of(&ctx.analyzer, &ctx.spec.target) else {
2540        return false;
2541    };
2542    let recovered_scope = ctx.recovered_sentinel_scope(node);
2543    let resolution = if let Some(recovered_scope) = recovered_scope {
2544        resolve_type_components_lexically_at_for_target_with_recovered_scope(
2545            node,
2546            owner_prefix,
2547            owner.global,
2548            &ctx.analyzer,
2549            ctx.visibility,
2550            &ctx.ordinary_type_imports,
2551            ctx.file,
2552            ctx.source,
2553            &parent,
2554            false,
2555            &recovered_scope,
2556        )
2557    } else {
2558        resolve_type_components_lexically_at_for_target_with_scope_cache(
2559            node,
2560            owner_prefix,
2561            owner.global,
2562            &ctx.analyzer,
2563            ctx.visibility,
2564            &ctx.ordinary_type_imports,
2565            ctx.file,
2566            ctx.source,
2567            &parent,
2568            false,
2569            Some(&ctx.lexical_scope_cache),
2570        )
2571    };
2572    let LexicalTypeResolution::Resolved {
2573        unit, candidates, ..
2574    } = resolution
2575    else {
2576        return false;
2577    };
2578    same_member_pointer_owner_identity(&unit, &parent)
2579        || candidates
2580            .iter()
2581            .any(|candidate| same_member_pointer_owner_identity(candidate, &parent))
2582}
2583
2584fn same_member_pointer_owner_identity(left: &CodeUnit, right: &CodeUnit) -> bool {
2585    same_visible_symbol(left, right)
2586        || (left.kind() == right.kind()
2587            && left.fq_name() == right.fq_name()
2588            && left.source() == right.source())
2589}
2590
2591/// Resolve a template type nested in a qualified identifier against a concrete
2592/// type target. The target-guided lexical path intentionally applies a
2593/// structured candidate prefilter; that prefilter cannot see a partial
2594/// specialization until the template arguments have selected it. Resolve the
2595/// complete qualified primary first, then apply the parsed arguments and
2596/// retain the result only when it is the requested target.
2597fn resolve_nested_template_type_for_target(
2598    node: Node<'_>,
2599    ctx: &ScanCtx<'_>,
2600) -> Option<LexicalTypeResolution> {
2601    let reference_node = node
2602        .parent()
2603        .filter(|parent| {
2604            parent.kind() == "qualified_identifier"
2605                && parent.child_by_field_name("name") == Some(node)
2606        })
2607        .unwrap_or(node);
2608    let target_resolution = resolve_type_node_lexically_for_target(
2609        reference_node,
2610        &ctx.analyzer,
2611        ctx.visibility,
2612        &ctx.ordinary_type_imports,
2613        ctx.file,
2614        ctx.source,
2615        &ctx.spec.target,
2616        Some(&ctx.lexical_scope_cache),
2617        ctx.recovered_sentinel_scope(reference_node).as_deref(),
2618    );
2619    if let LexicalTypeResolution::Resolved {
2620        unit, candidates, ..
2621    } = target_resolution
2622        && template_reference_candidates_select_target(
2623            reference_node,
2624            &candidates,
2625            &ctx.analyzer,
2626            ctx.visibility,
2627            ctx.file,
2628            ctx.source,
2629            &ctx.spec.target,
2630        )
2631    {
2632        return Some(LexicalTypeResolution::Resolved {
2633            unit,
2634            components: Vec::new(),
2635            candidates,
2636        });
2637    }
2638
2639    let normal_resolution = resolve_type_node_lexically(
2640        reference_node,
2641        &ctx.analyzer,
2642        ctx.visibility,
2643        &ctx.ordinary_type_imports,
2644        ctx.file,
2645        ctx.source,
2646    );
2647    let LexicalTypeResolution::Resolved {
2648        unit,
2649        components,
2650        candidates,
2651    } = normal_resolution
2652    else {
2653        return None;
2654    };
2655    let arguments = cpp_template_reference_arguments(reference_node, ctx.source)?;
2656    let specialized = ctx
2657        .visibility
2658        .resolve_template_arguments(ctx.file, unit.clone(), &arguments)
2659        .ok()
2660        .unwrap_or(unit);
2661    (same_visible_symbol(&specialized, &ctx.spec.target)
2662        || template_type_component_preserves_target(reference_node, &candidates, ctx))
2663    .then_some(LexicalTypeResolution::Resolved {
2664        unit: specialized,
2665        components,
2666        candidates,
2667    })
2668}
2669
2670fn type_reference_components_may_name_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
2671    let mut reference = node;
2672    while let Some(parent) = ctx.ancestry.parent(reference) {
2673        let owns_component = matches!(parent.kind(), "template_type" | "template_function")
2674            && parent.child_by_field_name("name") == Some(reference)
2675            || matches!(
2676                parent.kind(),
2677                "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
2678            ) && (parent.child_by_field_name("scope") == Some(reference)
2679                || parent.child_by_field_name("name") == Some(reference));
2680        if !owns_component {
2681            break;
2682        }
2683        reference = parent;
2684    }
2685    let Some((components, global)) = type_reference_components(reference, ctx.source) else {
2686        return false;
2687    };
2688    type_reference_component_list_may_name_target(
2689        &components,
2690        global,
2691        &ctx.analyzer,
2692        ctx.visibility,
2693        ctx.file,
2694        &ctx.spec.target,
2695        &ctx.type_reference_component_names,
2696    )
2697}
2698
2699fn type_reference_component_list_may_name_target(
2700    components: &[String],
2701    global: bool,
2702    analyzer: &CppGraphSource<'_>,
2703    visibility: &VisibilityIndex<'_>,
2704    file: &ProjectFile,
2705    target: &CodeUnit,
2706    reference_component_names: &HashSet<String>,
2707) -> bool {
2708    if components.iter().any(|component| {
2709        visibility.type_reference_component_directly_names_target(component, target)
2710    }) {
2711        return true;
2712    }
2713    if components.iter().any(|component| {
2714        visibility.parser_alias_name_may_resolve_to_target(file, component, target)
2715    }) {
2716        return true;
2717    }
2718    if components.len() > 1 {
2719        return visibility.qualified_alias_reference_may_reach_target(
2720            analyzer, file, components, global, target,
2721        );
2722    }
2723    components
2724        .iter()
2725        .any(|component| reference_component_names.contains(component))
2726}
2727
2728/// Fast structured admission before a type scan builds its parent and lexical
2729/// indexes. Most inverse candidates merely include the target's header and do
2730/// not contain a reference spelling; the full stateful scan has no work in
2731/// those files. Only maximal grammar type names are tested so a common nested
2732/// alias terminal such as `type` is considered together with its owner.
2733fn file_may_reference_type_target(
2734    root: Node<'_>,
2735    source: &str,
2736    analyzer: &CppGraphSource<'_>,
2737    visibility: &VisibilityIndex<'_>,
2738    file: &ProjectFile,
2739    target: &CodeUnit,
2740    reference_component_names: &HashSet<String>,
2741) -> bool {
2742    visit_file_type_reference_spellings(root, source, |components, global| {
2743        type_reference_component_list_may_name_target(
2744            components,
2745            global,
2746            analyzer,
2747            visibility,
2748            file,
2749            target,
2750            reference_component_names,
2751        )
2752    })
2753}
2754
2755fn visit_file_type_reference_spellings(
2756    root: Node<'_>,
2757    source: &str,
2758    mut visit: impl FnMut(&[String], bool) -> bool,
2759) -> bool {
2760    let mut stopped = false;
2761    walk_named_tree_preorder(root, true, |node| {
2762        if node.kind() == "comment" {
2763            return WalkControl::SkipChildren;
2764        }
2765        if node.kind() == "preproc_arg" {
2766            stopped = object_macro_replacement_type_references(node, source)
2767                .into_iter()
2768                .any(|reference| visit(&reference.components, reference.global));
2769            return if stopped {
2770                WalkControl::Break
2771            } else {
2772                WalkControl::SkipChildren
2773            };
2774        }
2775        if node.kind() == "field_declaration"
2776            && let Some(return_type) = recovered_macro_return_type_node(node, source)
2777        {
2778            let components = [node_text(return_type, source).to_string()];
2779            stopped = visit(&components, false);
2780            if stopped {
2781                return WalkControl::Break;
2782            }
2783        }
2784        if let Some((type_node, _)) = recovered_macro_decorated_type_node(node) {
2785            for candidate in [node, type_node] {
2786                let Some((components, global)) = type_reference_components(candidate, source)
2787                else {
2788                    continue;
2789                };
2790                stopped = visit(&components, global);
2791                if stopped {
2792                    return WalkControl::Break;
2793                }
2794            }
2795        }
2796        let Some((components, global)) = type_reference_components(node, source) else {
2797            return WalkControl::Continue;
2798        };
2799        if node.parent().is_some_and(|parent| {
2800            (matches!(parent.kind(), "template_type" | "template_function")
2801                && parent.child_by_field_name("name") == Some(node))
2802                || (matches!(
2803                    parent.kind(),
2804                    "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
2805                ) && (parent.child_by_field_name("scope") == Some(node)
2806                    || parent.child_by_field_name("name") == Some(node)))
2807        }) {
2808            return WalkControl::Continue;
2809        }
2810        stopped = visit(&components, global);
2811        if stopped {
2812            WalkControl::Break
2813        } else {
2814            WalkControl::Continue
2815        }
2816    });
2817    stopped
2818}
2819
2820/// Whether this file decides the reference against the scan target.
2821///
2822/// The last resort of type admission has no structured resolution left: it
2823/// only knows that the spelling mentions the target's name and that the target
2824/// itself is not visible here. That is undecidable when nothing else declares
2825/// the name, but it is a proven negative when the file already makes another
2826/// declaration of the same name visible, because unqualified lookup binds the
2827/// reference to that declaration and the include closure never reaches the
2828/// target. `resolve_type_node_lexically_for_target` asks the visibility index
2829/// the same question before it resolves; asking it again here keeps the
2830/// inverse from admitting a site that forward resolution has already decided
2831/// (#2916).
2832fn type_reference_resolves_away_from_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
2833    let Some((components, _global)) = type_reference_components(node, ctx.source) else {
2834        return false;
2835    };
2836    let terminal = components
2837        .last()
2838        .expect("type reference components are non-empty");
2839    if terminal != ctx.spec.target.identifier() {
2840        return false;
2841    }
2842    // A concrete specialization is selected from the template arguments, not
2843    // from the visible primary name, so the name-level candidate set cannot
2844    // decide it. `resolve_type_node_lexically_for_target` makes the same
2845    // exception before its own structured prefilter.
2846    if cpp_template_reference_arguments(node, ctx.source).is_some()
2847        && ctx.visibility.is_template_specialization(&ctx.spec.target)
2848    {
2849        return false;
2850    }
2851    // One C++ type reached through a forward declaration in one header and its
2852    // definition in another is two CodeUnits with different signatures and one
2853    // qualified name. A file that sees either of them sees the target's type,
2854    // so only a candidate under a different qualified name decides the
2855    // reference against it. This is what separates the decoy in an unrelated
2856    // namespace from a redeclaration of the target itself.
2857    if ctx
2858        .visibility
2859        .visible_identifier_candidates(ctx.file, terminal)
2860        .any(|candidate| {
2861            candidate.kind() == ctx.spec.target.kind()
2862                && candidate.fq_name() == ctx.spec.target.fq_name()
2863        })
2864    {
2865        return false;
2866    }
2867    !ctx.visibility
2868        .structured_type_reference_may_resolve_to_target(
2869            &ctx.analyzer,
2870            ctx.file,
2871            std::slice::from_ref(terminal),
2872            false,
2873            &[],
2874            &ctx.spec.target,
2875        )
2876}
2877
2878fn qualified_type_scope_contains_template(node: Node<'_>) -> bool {
2879    let Some(scope) = node.child_by_field_name("scope") else {
2880        return false;
2881    };
2882    let mut pending = vec![scope];
2883    while let Some(candidate) = pending.pop() {
2884        if candidate.kind() == "template_type" {
2885            return true;
2886        }
2887        if matches!(
2888            candidate.kind(),
2889            "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
2890        ) {
2891            if let Some(scope) = candidate.child_by_field_name("scope") {
2892                pending.push(scope);
2893            }
2894            if let Some(name) = candidate.child_by_field_name("name") {
2895                pending.push(name);
2896            }
2897        }
2898    }
2899    false
2900}
2901
2902fn physically_visible_type_target<'a>(ctx: &'a ScanCtx<'_>) -> Option<&'a CodeUnit> {
2903    ctx.target_group.iter().find(|target| {
2904        same_logical_symbol(target, &ctx.spec.target)
2905            && ctx.visibility.is_physically_visible(ctx.file, target)
2906    })
2907}
2908
2909/// Preserve the terminal token of a resolver-proven alias construction.
2910/// Ordinary qualified types and template aliases retain their full type range.
2911/// Alias identity and the construction context are proven by the resolver.
2912fn push_resolved_type_hit(node: Node<'_>, candidates: &[CodeUnit], ctx: &mut ScanCtx<'_>) {
2913    if let Some(terminal) = resolved_alias_terminal_node(node, candidates, ctx) {
2914        push_type_hit_range(terminal, terminal.start_byte(), terminal.end_byte(), ctx);
2915    } else {
2916        push_type_hit(type_reference_hit_node(node), ctx);
2917    }
2918}
2919
2920fn resolved_alias_terminal_node<'tree>(
2921    node: Node<'tree>,
2922    candidates: &[CodeUnit],
2923    ctx: &ScanCtx<'_>,
2924) -> Option<Node<'tree>> {
2925    let [candidate] = candidates else {
2926        return None;
2927    };
2928    let alias_provider = ctx.analyzer.type_alias_provider()?;
2929    let candidate_is_alias = alias_provider.is_type_alias(candidate)
2930        && same_visible_symbol(&canonical_alias_target(candidate, ctx), &ctx.spec.target);
2931    let target_is_alias = alias_provider.is_type_alias(&ctx.spec.target)
2932        && same_visible_symbol(candidate, &ctx.spec.target);
2933    if !(candidate_is_alias || target_is_alias) {
2934        return None;
2935    }
2936    if crate::graph::resolver::cpp_template_reference_arguments(node, ctx.source).is_some() {
2937        return None;
2938    }
2939    let reference = crate::graph::resolver::qualified_alias_reference_preserves_target(
2940        node,
2941        &ctx.spec.target,
2942        &ctx.analyzer,
2943        ctx.visibility,
2944        ctx.file,
2945        ctx.source,
2946    );
2947    if reference
2948        != Some(
2949            crate::graph::resolver::QualifiedAliasReferenceKind::ConstructorWithExpressionArgument,
2950        )
2951    {
2952        return None;
2953    }
2954    cpp_name_component_nodes(node)?.last().copied()
2955}
2956
2957fn target_guided_missing_direct_temporary_type<'tree>(
2958    function: Node<'tree>,
2959    ctx: &ScanCtx<'_>,
2960) -> Option<Node<'tree>> {
2961    let target = physically_visible_type_target(ctx)?;
2962    let component_nodes = cpp_name_component_nodes(function)?;
2963    let terminal = component_nodes.last().copied()?;
2964    if node_text(terminal, ctx.source) != target.identifier() {
2965        return None;
2966    }
2967    let components = component_nodes
2968        .iter()
2969        .map(|component| node_text(*component, ctx.source).to_string())
2970        .collect::<Vec<_>>();
2971    let indexed_scope = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, function)?;
2972    indexed_scope_matches_target_name(
2973        &indexed_scope,
2974        &components,
2975        is_globally_qualified_cpp_name(function),
2976        target,
2977    )
2978    .then_some(terminal)
2979}
2980
2981fn maybe_record_direct_temporary_type_hit(call: Node<'_>, ctx: &mut ScanCtx<'_>) {
2982    let Some(function) = call.child_by_field_name("function") else {
2983        return;
2984    };
2985    if !matches!(
2986        function.kind(),
2987        "identifier"
2988            | "type_identifier"
2989            | "template_function"
2990            | "template_type"
2991            | "qualified_identifier"
2992            | "scoped_identifier"
2993            | "scoped_type_identifier"
2994    ) {
2995        return;
2996    }
2997    if !type_reference_components_may_name_target(function, ctx) {
2998        return;
2999    }
3000    if let Some(scopes) = static_qualifier_type_scopes(function, ctx) {
3001        *ctx.raw_match_count += 1;
3002        for scope in scopes {
3003            push_type_hit(scope, ctx);
3004        }
3005        return;
3006    }
3007    let terminal = function_terminal_node(function);
3008    let name = node_text(terminal, ctx.source);
3009    if name.is_empty() || ctx.local_shadows.is_shadowed(name) {
3010        return;
3011    }
3012    if let Some(enclosing_owner) = structured_enclosing_owner(function, ctx) {
3013        match resolve_declaring_member_owner(
3014            &ctx.analyzer,
3015            ctx.visibility,
3016            ctx.file,
3017            &enclosing_owner,
3018            name,
3019        ) {
3020            EnclosingMemberOwnerResolution::Owner(owner)
3021                if matches!(
3022                    ctx.visibility
3023                        .visible_member_for_owner_name(ctx.file, &owner, name,),
3024                    VisibleMemberResolution::Callable(_) | VisibleMemberResolution::AmbiguousKind
3025                ) =>
3026            {
3027                return;
3028            }
3029            EnclosingMemberOwnerResolution::Ambiguous => return,
3030            EnclosingMemberOwnerResolution::Owner(_) | EnclosingMemberOwnerResolution::Missing => {}
3031        }
3032    }
3033
3034    // A type alias used as a direct temporary (`result_type(value)`) is parsed
3035    // as an ordinary identifier call. Callable lookup can be ambiguous when
3036    // parser recovery flattens a namespace or same-spelled aliases are
3037    // visible from sibling distributions. An exact enclosing class owner
3038    // proves the member alias without treating the call as an arbitrary name;
3039    // retain the shadow and declaration-visibility guards above and below.
3040    if ctx
3041        .analyzer
3042        .type_alias_provider()
3043        .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
3044        && name == ctx.spec.target.identifier()
3045        && physically_visible_type_target(ctx).is_some()
3046        && !local_type_name_shadows(function, ctx)
3047        && type_alias_owner_matches_structured_reference(function, ctx)
3048        && ctx.visibility.external_type_candidate_visible_in_context(
3049            &ctx.analyzer,
3050            ctx.file,
3051            &ctx.spec.target,
3052            function,
3053        )
3054    {
3055        *ctx.raw_match_count += 1;
3056        push_type_hit(terminal, ctx);
3057        return;
3058    }
3059
3060    let call_resolution = resolve_qualified_call_target(
3061        call,
3062        function,
3063        &ctx.analyzer,
3064        ctx.visibility,
3065        &ctx.ordinary_type_imports,
3066        ctx.file,
3067        ctx.source,
3068    );
3069    match call_resolution {
3070        BareCallTargetResolution::Type(unit) => {
3071            if same_visible_symbol(&unit, &ctx.spec.target) {
3072                *ctx.raw_match_count += 1;
3073                push_type_hit(function, ctx);
3074                return;
3075            }
3076        }
3077        BareCallTargetResolution::FreeFunctions(units)
3078            if units.iter().all(|unit| {
3079                unit.fq_name() == ctx.spec.target.fq_name()
3080                    && ctx
3081                        .visibility
3082                        .callable_is_constructor_declaration(&ctx.analyzer, unit)
3083            }) => {}
3084        BareCallTargetResolution::Ambiguous => {
3085            push_unproven_hit(function, ctx);
3086            return;
3087        }
3088        BareCallTargetResolution::FreeFunctions(_)
3089        | BareCallTargetResolution::UnprovenFreeFunctions(_)
3090        | BareCallTargetResolution::CallableShadow => return,
3091        // Generated `.c` includes can leave ordinary callable resolution with
3092        // no active callable even when target-preserving type resolution can
3093        // prove the constructor's class. Let the structured type fallback
3094        // below make that decision.
3095        BareCallTargetResolution::Missing => {}
3096    }
3097    let target_resolution = resolve_type_node_lexically_for_target(
3098        function,
3099        &ctx.analyzer,
3100        ctx.visibility,
3101        &ctx.ordinary_type_imports,
3102        ctx.file,
3103        ctx.source,
3104        &ctx.spec.target,
3105        Some(&ctx.lexical_scope_cache),
3106        ctx.recovered_sentinel_scope(function).as_deref(),
3107    );
3108    match target_resolution {
3109        LexicalTypeResolution::Resolved {
3110            unit, candidates, ..
3111        } if same_visible_symbol(&unit, &ctx.spec.target)
3112            || candidates
3113                .iter()
3114                .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target)) =>
3115        {
3116            *ctx.raw_match_count += 1;
3117            push_type_hit(function, ctx);
3118        }
3119        LexicalTypeResolution::Missing => {
3120            if let Some(hit) = target_guided_nested_type_terminal_hit(terminal, ctx)
3121                .or_else(|| target_guided_missing_direct_temporary_type(function, ctx))
3122            {
3123                *ctx.raw_match_count += 1;
3124                push_type_hit(hit, ctx);
3125            }
3126        }
3127        LexicalTypeResolution::Resolved { .. } | LexicalTypeResolution::Ambiguous => {}
3128    }
3129}
3130
3131pub enum BareCallTargetResolution {
3132    Type(CodeUnit),
3133    FreeFunctions(Vec<CodeUnit>),
3134    UnprovenFreeFunctions(Vec<CodeUnit>),
3135    CallableShadow,
3136    Ambiguous,
3137    Missing,
3138}
3139
3140pub enum BlockUsingCallTargetResolution {
3141    Target(BareCallTargetResolution),
3142    Unindexed(Vec<String>),
3143    Ambiguous,
3144}
3145
3146#[allow(clippy::too_many_arguments)]
3147fn resolve_qualified_call_target(
3148    call: Node<'_>,
3149    function: Node<'_>,
3150    analyzer: &CppGraphSource<'_>,
3151    visibility: &VisibilityIndex,
3152    ordinary_type_imports: &OrdinaryTypeImportCell,
3153    file: &ProjectFile,
3154    source: &str,
3155) -> BareCallTargetResolution {
3156    if matches!(function.kind(), "identifier" | "template_function") {
3157        return resolve_bare_call_target(
3158            call,
3159            function,
3160            analyzer,
3161            visibility,
3162            ordinary_type_imports,
3163            file,
3164            source,
3165        );
3166    }
3167    if !matches!(
3168        function.kind(),
3169        "qualified_identifier" | "scoped_identifier" | "scoped_type_identifier"
3170    ) {
3171        return BareCallTargetResolution::Missing;
3172    }
3173    let terminal = function_terminal_node(function);
3174    let name = node_text(terminal, source);
3175    let Some((mut components, _)) = qualified_callable_owner_components(function, source) else {
3176        return BareCallTargetResolution::Missing;
3177    };
3178    components.push(name.to_string());
3179    let qualified_name = components.join("::");
3180    let type_resolution = resolve_type_node_lexically(
3181        function,
3182        analyzer,
3183        visibility,
3184        ordinary_type_imports,
3185        file,
3186        source,
3187    );
3188    let same_name_resolves_to_type = matches!(
3189        &type_resolution,
3190        LexicalTypeResolution::Resolved {
3191            unit,
3192            candidates,
3193            ..
3194        } if cpp_name_for(unit) == qualified_name
3195            || candidates
3196                .iter()
3197                .any(|candidate| cpp_name_for(candidate) == qualified_name)
3198    );
3199    let has_explicit_template_arguments =
3200        cpp_template_reference_arguments(function, source).is_some();
3201    let candidates = visibility
3202        .visible_identifier_candidates(file, name)
3203        .filter(|candidate| {
3204            candidate.is_function()
3205                && type_owner_of(analyzer, candidate).is_none()
3206                && !(same_name_resolves_to_type
3207                    && (visibility.callable_is_constructor_declaration(analyzer, candidate)
3208                        || has_explicit_template_arguments
3209                            && visibility
3210                                .callable_is_deduction_guide_declaration(analyzer, candidate)))
3211                && cpp_name_for(candidate) == qualified_name
3212                && visibility.declaration_visible_at(analyzer, file, candidate, call.start_byte())
3213        })
3214        .cloned()
3215        .collect::<Vec<_>>();
3216    if !candidates.is_empty() {
3217        return resolve_callable_candidates(
3218            candidates,
3219            visibility.call_arity_evidence(file, call, source).exact(),
3220            call.start_byte(),
3221            analyzer,
3222            visibility,
3223            file,
3224        );
3225    }
3226    match type_resolution {
3227        LexicalTypeResolution::Resolved { unit, .. } => BareCallTargetResolution::Type(unit),
3228        LexicalTypeResolution::Ambiguous => BareCallTargetResolution::Ambiguous,
3229        LexicalTypeResolution::Missing => BareCallTargetResolution::Missing,
3230    }
3231}
3232
3233fn ordinary_binding_lookup_targets(
3234    binding: &OrdinaryTypeImport,
3235    active_bindings: &[&OrdinaryTypeImport],
3236    name: &str,
3237) -> Vec<Vec<String>> {
3238    let Some(qualified) = binding.resolved_target_components.as_ref() else {
3239        return Vec::new();
3240    };
3241    let mut targets = Vec::new();
3242    match binding.target {
3243        EffectiveUsingTarget::Ordinary { .. } => targets.push(qualified.clone()),
3244        EffectiveUsingTarget::Namespace { .. } => {
3245            let mut stack = vec![qualified.clone()];
3246            let mut visited = HashSet::default();
3247            while let Some(namespace) = stack.pop() {
3248                if !visited.insert(namespace.clone()) {
3249                    continue;
3250                }
3251                let mut target = namespace.clone();
3252                target.push(name.to_string());
3253                targets.push(target);
3254                stack.extend(active_bindings.iter().filter_map(|candidate| {
3255                    (matches!(candidate.target, EffectiveUsingTarget::Namespace { .. })
3256                        && candidate.namespace_scope.as_deref() == Some(namespace.as_slice()))
3257                    .then(|| candidate.resolved_target_components.clone())
3258                    .flatten()
3259                }));
3260            }
3261        }
3262    }
3263    targets
3264}
3265
3266fn binding_free_function_candidates(
3267    binding: &OrdinaryTypeImport,
3268    active_bindings: &[&OrdinaryTypeImport],
3269    analyzer: &CppGraphSource<'_>,
3270    visibility: &VisibilityIndex<'_>,
3271    file: &ProjectFile,
3272    name: &str,
3273    reference_byte: usize,
3274) -> Vec<CodeUnit> {
3275    ordinary_binding_lookup_targets(binding, active_bindings, name)
3276        .into_iter()
3277        .flat_map(|target| {
3278            let qualified_name = target.join("::");
3279            visibility
3280                .visible_identifier_candidates(file, name)
3281                .filter(move |candidate| {
3282                    candidate.is_function()
3283                        && type_owner_of(analyzer, candidate).is_none()
3284                        && cpp_name_for(candidate) == qualified_name
3285                        && visibility.declaration_visible_at(
3286                            analyzer,
3287                            file,
3288                            candidate,
3289                            reference_byte,
3290                        )
3291                })
3292                .cloned()
3293        })
3294        .collect()
3295}
3296
3297/// Collapse the candidates unqualified lookup found to one entry per logical
3298/// callable, keeping the first spelling of each.
3299///
3300/// A header declaration and its out-of-line body spell one parameter type
3301/// differently often enough that the persisted signature strings disagree, so
3302/// the string triple alone reports one C++ declaration as an overload set and
3303/// an unproven argument count then turns it into ambiguity.
3304/// `same_logical_callable` answers the string question first and resolves the
3305/// written parameter names only when the strings differ (#2010).
3306fn dedupe_callable_candidates(
3307    candidates: &mut Vec<CodeUnit>,
3308    analyzer: &CppGraphSource<'_>,
3309    visibility: &VisibilityIndex<'_>,
3310) {
3311    let mut deduped = Vec::with_capacity(candidates.len());
3312    for candidate in candidates.drain(..) {
3313        if !deduped
3314            .iter()
3315            .any(|existing| visibility.same_logical_callable(analyzer, existing, &candidate))
3316        {
3317            deduped.push(candidate);
3318        }
3319    }
3320    *candidates = deduped;
3321}
3322
3323fn resolve_callable_candidates(
3324    candidates: Vec<CodeUnit>,
3325    call_arity: Option<usize>,
3326    reference_byte: usize,
3327    analyzer: &CppGraphSource<'_>,
3328    visibility: &VisibilityIndex<'_>,
3329    file: &ProjectFile,
3330) -> BareCallTargetResolution {
3331    let mut candidates = candidates;
3332    dedupe_callable_candidates(&mut candidates, analyzer, visibility);
3333    if candidates.is_empty() {
3334        return BareCallTargetResolution::Missing;
3335    }
3336    let Some(call_arity) = call_arity else {
3337        // An unproven argument count cannot create ambiguity where lookup found
3338        // exactly one name binding: there is nothing to be ambiguous between.
3339        // C has no overloading at all, and a lone C++ candidate is the only
3340        // declaration unqualified lookup reached, so arity cannot pick another
3341        // one (#1811). Keeping it unproven discarded the proven candidate and
3342        // answered `ambiguous` with an empty definition list.
3343        if candidates.len() == 1 {
3344            return BareCallTargetResolution::FreeFunctions(candidates);
3345        }
3346        return BareCallTargetResolution::UnprovenFreeFunctions(candidates);
3347    };
3348    let applicable = candidates
3349        .into_iter()
3350        .filter(|candidate| {
3351            visibility
3352                .callable_arity_at_reference(analyzer, file, candidate, reference_byte)
3353                .is_some_and(|arity| arity.accepts(call_arity))
3354        })
3355        .collect::<Vec<_>>();
3356    if applicable.is_empty() {
3357        BareCallTargetResolution::CallableShadow
3358    } else {
3359        BareCallTargetResolution::FreeFunctions(applicable)
3360    }
3361}
3362
3363fn deduplicate_type_import_candidates(
3364    candidates: Vec<(CodeUnit, Vec<String>)>,
3365) -> Vec<(CodeUnit, Vec<String>)> {
3366    let mut logical = Vec::<(CodeUnit, Vec<String>)>::new();
3367    for candidate in candidates {
3368        if !logical
3369            .iter()
3370            .any(|(existing, _)| same_logical_symbol(existing, &candidate.0))
3371        {
3372            logical.push(candidate);
3373        }
3374    }
3375    logical
3376}
3377
3378fn resolve_direct_type_candidates(
3379    candidates: Vec<(CodeUnit, Vec<String>)>,
3380    analyzer: &CppGraphSource<'_>,
3381    visibility: &VisibilityIndex<'_>,
3382    file: &ProjectFile,
3383) -> BareCallTargetResolution {
3384    let logical = deduplicate_type_import_candidates(candidates);
3385    let [(target, components)] = logical.as_slice() else {
3386        return if logical.is_empty() {
3387            BareCallTargetResolution::Missing
3388        } else {
3389            BareCallTargetResolution::Ambiguous
3390        };
3391    };
3392    match visibility
3393        .resolve_imported_type_candidate(analyzer, file, target, components, None, false)
3394    {
3395        LexicalTypeResolution::Resolved { unit, .. } => BareCallTargetResolution::Type(unit),
3396        LexicalTypeResolution::Ambiguous => BareCallTargetResolution::Ambiguous,
3397        LexicalTypeResolution::Missing => BareCallTargetResolution::Missing,
3398    }
3399}
3400
3401/// Resolve a direct using-declaration in the nearest concrete block before
3402/// class-member lookup. A block declaration such as `using std::swap;` adds
3403/// that name to the block scope and hides a same-named member. If the imported
3404/// target is not indexed, retain its structured path as boundary evidence.
3405#[allow(clippy::too_many_arguments)]
3406pub fn resolve_block_using_call_target(
3407    call: Node<'_>,
3408    function: Node<'_>,
3409    analyzer: &CppGraphSource<'_>,
3410    visibility: &VisibilityIndex<'_>,
3411    ordinary_type_imports: &OrdinaryTypeImportCell,
3412    file: &ProjectFile,
3413    source: &str,
3414) -> Option<BlockUsingCallTargetResolution> {
3415    if !matches!(function.kind(), "identifier" | "template_function") {
3416        return None;
3417    }
3418    let name = node_text(function_terminal_node(function), source);
3419    if name.is_empty() {
3420        return None;
3421    }
3422    let bindings = effective_using_bindings_for_name(
3423        visibility,
3424        ordinary_type_imports,
3425        file,
3426        function,
3427        source,
3428        name,
3429    );
3430    let block_bindings = bindings
3431        .iter()
3432        .filter(|binding| {
3433            binding.namespace_scope.is_none()
3434                && binding.block_scope
3435                && matches!(binding.target, EffectiveUsingTarget::Ordinary { .. })
3436        })
3437        .collect::<Vec<_>>();
3438    if block_bindings.is_empty() {
3439        return None;
3440    }
3441    let lexical_scope =
3442        match enclosing_lexical_scope_components(function, analyzer, visibility, file, source) {
3443            LexicalScopeResolution::Resolved(scope) => scope,
3444            LexicalScopeResolution::Ambiguous => {
3445                return Some(BlockUsingCallTargetResolution::Ambiguous);
3446            }
3447            LexicalScopeResolution::Missing => return None,
3448        };
3449    let reference_guards = preprocessor_guard_environment(function, source);
3450    let active = block_bindings
3451        .into_iter()
3452        .filter(|binding| {
3453            effective_using_binding_active(
3454                binding,
3455                function,
3456                &lexical_scope,
3457                reference_guards.as_ref(),
3458                visibility,
3459                file,
3460            )
3461        })
3462        .collect::<Vec<_>>();
3463    let depth = active.iter().map(|binding| binding.scope_depth).max()?;
3464    let at_tier = active
3465        .into_iter()
3466        .filter(|binding| binding.scope_depth == depth)
3467        .collect::<Vec<_>>();
3468    let callable_candidates = at_tier
3469        .iter()
3470        .flat_map(|binding| {
3471            binding_free_function_candidates(
3472                binding,
3473                &[],
3474                analyzer,
3475                visibility,
3476                file,
3477                name,
3478                call.start_byte(),
3479            )
3480        })
3481        .collect::<Vec<_>>();
3482    if !callable_candidates.is_empty() {
3483        return Some(BlockUsingCallTargetResolution::Target(
3484            resolve_callable_candidates(
3485                callable_candidates,
3486                visibility.call_arity_evidence(file, call, source).exact(),
3487                call.start_byte(),
3488                analyzer,
3489                visibility,
3490                file,
3491            ),
3492        ));
3493    }
3494    let type_candidates = at_tier
3495        .iter()
3496        .flat_map(|binding| {
3497            binding_type_candidates(
3498                binding,
3499                &[],
3500                analyzer,
3501                visibility,
3502                file,
3503                name,
3504                None,
3505                call.start_byte(),
3506            )
3507        })
3508        .collect::<Vec<_>>();
3509    if !type_candidates.is_empty() {
3510        return Some(BlockUsingCallTargetResolution::Target(
3511            resolve_direct_type_candidates(type_candidates, analyzer, visibility, file),
3512        ));
3513    }
3514
3515    let mut unindexed = Vec::new();
3516    for binding in at_tier {
3517        let Some(components) = binding.resolved_target_components.as_ref() else {
3518            continue;
3519        };
3520        if !unindexed.contains(components) {
3521            unindexed.push(components.clone());
3522        }
3523    }
3524    match unindexed.as_slice() {
3525        [target] => Some(BlockUsingCallTargetResolution::Unindexed(target.clone())),
3526        [] => None,
3527        _ => Some(BlockUsingCallTargetResolution::Ambiguous),
3528    }
3529}
3530
3531#[allow(clippy::too_many_arguments)]
3532pub fn resolve_bare_call_target(
3533    call: Node<'_>,
3534    function: Node<'_>,
3535    analyzer: &CppGraphSource<'_>,
3536    visibility: &VisibilityIndex<'_>,
3537    ordinary_type_imports: &OrdinaryTypeImportCell,
3538    file: &ProjectFile,
3539    source: &str,
3540) -> BareCallTargetResolution {
3541    if !matches!(function.kind(), "identifier" | "template_function") {
3542        return BareCallTargetResolution::Missing;
3543    }
3544    let terminal = function_terminal_node(function);
3545    let name = node_text(terminal, source);
3546    if name.is_empty() {
3547        return BareCallTargetResolution::Missing;
3548    }
3549    let call_arity = visibility.call_arity_evidence(file, call, source).exact();
3550    let lexical_scope =
3551        match enclosing_lexical_scope_components(function, analyzer, visibility, file, source) {
3552            LexicalScopeResolution::Resolved(scope) => scope,
3553            LexicalScopeResolution::Ambiguous => return BareCallTargetResolution::Ambiguous,
3554            LexicalScopeResolution::Missing => return BareCallTargetResolution::Missing,
3555        };
3556    let type_resolution = resolve_type_node_lexically(
3557        function,
3558        analyzer,
3559        visibility,
3560        ordinary_type_imports,
3561        file,
3562        source,
3563    );
3564    let type_components = match &type_resolution {
3565        LexicalTypeResolution::Resolved { components, .. } => Some(components.as_slice()),
3566        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
3567    };
3568    let direct_type_resolution = visibility.resolve_type_components_lexically(
3569        analyzer,
3570        file,
3571        &[name.to_string()],
3572        false,
3573        &lexical_scope,
3574    );
3575    let direct_type_components = match &direct_type_resolution {
3576        LexicalTypeResolution::Resolved { components, .. } => Some(components.as_slice()),
3577        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
3578    };
3579    let has_explicit_template_arguments =
3580        cpp_template_reference_arguments(function, source).is_some();
3581    let bindings = effective_using_bindings_for_name(
3582        visibility,
3583        ordinary_type_imports,
3584        file,
3585        function,
3586        source,
3587        name,
3588    );
3589    // Guard ancestry climbs the whole ancestor chain and each `Node::parent`
3590    // step re-descends from the root (#1927): with no bindings both filters
3591    // below select nothing, so the environment is never consulted.
3592    let function_guards = if bindings.is_empty() {
3593        None
3594    } else {
3595        preprocessor_guard_environment(function, source)
3596    };
3597    let active_bindings = bindings
3598        .iter()
3599        .filter(|binding| {
3600            effective_using_binding_active(
3601                binding,
3602                function,
3603                &lexical_scope,
3604                function_guards.as_ref(),
3605                visibility,
3606                file,
3607            )
3608        })
3609        .collect::<Vec<_>>();
3610    let transitive_bindings = bindings
3611        .iter()
3612        .filter(|binding| {
3613            effective_using_binding_guards_active(
3614                binding,
3615                function.start_byte(),
3616                function_guards.as_ref(),
3617                visibility,
3618                file,
3619            ) && (binding.namespace_scope.is_some()
3620                || (binding.scope_start <= function.start_byte()
3621                    && function.end_byte() <= binding.scope_end))
3622        })
3623        .collect::<Vec<_>>();
3624    let mut concrete_depths = active_bindings
3625        .iter()
3626        .filter(|binding| binding.namespace_scope.is_none())
3627        .map(|binding| binding.scope_depth)
3628        .collect::<Vec<_>>();
3629    concrete_depths.sort_unstable();
3630    concrete_depths.dedup();
3631    for depth in concrete_depths.into_iter().rev() {
3632        let at_tier = active_bindings
3633            .iter()
3634            .copied()
3635            .filter(|binding| binding.namespace_scope.is_none() && binding.scope_depth == depth);
3636        let direct = at_tier
3637            .clone()
3638            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
3639            .flat_map(|binding| {
3640                binding_free_function_candidates(
3641                    binding,
3642                    &transitive_bindings,
3643                    analyzer,
3644                    visibility,
3645                    file,
3646                    name,
3647                    call.start_byte(),
3648                )
3649            })
3650            .collect::<Vec<_>>();
3651        if !direct.is_empty() {
3652            return resolve_callable_candidates(
3653                direct,
3654                call_arity,
3655                call.start_byte(),
3656                analyzer,
3657                visibility,
3658                file,
3659            );
3660        }
3661        let direct_types = at_tier
3662            .clone()
3663            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
3664            .flat_map(|binding| {
3665                binding_type_candidates(
3666                    binding,
3667                    &transitive_bindings,
3668                    analyzer,
3669                    visibility,
3670                    file,
3671                    name,
3672                    None,
3673                    call.start_byte(),
3674                )
3675            })
3676            .collect::<Vec<_>>();
3677        if !direct_types.is_empty() {
3678            // `resolve_direct_type_candidates` never consults the argument
3679            // count: it answers the one type the name binds to, or reports the
3680            // competing types. An unknown count therefore cannot make this
3681            // ambiguous (#1812).
3682            return resolve_direct_type_candidates(direct_types, analyzer, visibility, file);
3683        }
3684        let directives = at_tier
3685            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
3686            .flat_map(|binding| {
3687                binding_free_function_candidates(
3688                    binding,
3689                    &transitive_bindings,
3690                    analyzer,
3691                    visibility,
3692                    file,
3693                    name,
3694                    call.start_byte(),
3695                )
3696            })
3697            .collect::<Vec<_>>();
3698        if !directives.is_empty() {
3699            return resolve_callable_candidates(
3700                directives,
3701                call_arity,
3702                call.start_byte(),
3703                analyzer,
3704                visibility,
3705                file,
3706            );
3707        }
3708    }
3709    for prefix_len in (0..=lexical_scope.len()).rev() {
3710        let mut qualified = lexical_scope[..prefix_len].to_vec();
3711        qualified.push(name.to_string());
3712        let same_name_resolves_to_type = direct_type_components
3713            .is_some_and(|components| components == qualified.as_slice())
3714            || type_components.is_some_and(|components| components == qualified.as_slice());
3715        let mut direct = visibility
3716            .visible_identifier_candidates(file, name)
3717            .filter(|candidate| {
3718                candidate.is_function()
3719                    && type_owner_of(analyzer, candidate).is_none()
3720                    && !(same_name_resolves_to_type
3721                        && (visibility.callable_is_constructor_declaration(analyzer, candidate)
3722                            || has_explicit_template_arguments
3723                                && visibility
3724                                    .callable_is_deduction_guide_declaration(analyzer, candidate)))
3725                    && cpp_name_for(candidate) == qualified.join("::")
3726                    && if analyzer.reference_uses_c_semantics(file) {
3727                        visibility.declaration_visible_for_c_forward_call(
3728                            analyzer,
3729                            file,
3730                            candidate,
3731                            call.start_byte(),
3732                        )
3733                    } else {
3734                        visibility.declaration_visible_at(
3735                            analyzer,
3736                            file,
3737                            candidate,
3738                            call.start_byte(),
3739                        )
3740                    }
3741            })
3742            .cloned()
3743            .collect::<Vec<_>>();
3744        let at_tier = active_bindings.iter().copied().filter(|binding| {
3745            binding.namespace_scope.as_deref() == Some(&lexical_scope[..prefix_len])
3746        });
3747        direct.extend(
3748            at_tier
3749                .clone()
3750                .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
3751                .flat_map(|binding| {
3752                    binding_free_function_candidates(
3753                        binding,
3754                        &transitive_bindings,
3755                        analyzer,
3756                        visibility,
3757                        file,
3758                        name,
3759                        call.start_byte(),
3760                    )
3761                }),
3762        );
3763        if !direct.is_empty() {
3764            return resolve_callable_candidates(
3765                direct,
3766                call_arity,
3767                call.start_byte(),
3768                analyzer,
3769                visibility,
3770                file,
3771            );
3772        }
3773        let mut direct_types = at_tier
3774            .clone()
3775            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
3776            .flat_map(|binding| {
3777                binding_type_candidates(
3778                    binding,
3779                    &transitive_bindings,
3780                    analyzer,
3781                    visibility,
3782                    file,
3783                    name,
3784                    None,
3785                    call.start_byte(),
3786                )
3787            })
3788            .collect::<Vec<_>>();
3789        if direct_type_components.is_some_and(|components| components == qualified.as_slice())
3790            && let LexicalTypeResolution::Resolved {
3791                unit, components, ..
3792            } = &direct_type_resolution
3793        {
3794            direct_types.push((unit.clone(), components.clone()));
3795        }
3796        if !direct_types.is_empty() {
3797            // `resolve_direct_type_candidates` never consults the argument
3798            // count: it answers the one type the name binds to, or reports the
3799            // competing types. An unknown count therefore cannot make this
3800            // ambiguous (#1812).
3801            return resolve_direct_type_candidates(direct_types, analyzer, visibility, file);
3802        }
3803        let directives = at_tier
3804            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
3805            .flat_map(|binding| {
3806                binding_free_function_candidates(
3807                    binding,
3808                    &transitive_bindings,
3809                    analyzer,
3810                    visibility,
3811                    file,
3812                    name,
3813                    call.start_byte(),
3814                )
3815            })
3816            .collect::<Vec<_>>();
3817        if !directives.is_empty() {
3818            return resolve_callable_candidates(
3819                directives,
3820                call_arity,
3821                call.start_byte(),
3822                analyzer,
3823                visibility,
3824                file,
3825            );
3826        }
3827        if type_components.is_some_and(|components| components == qualified.as_slice()) {
3828            // The lexical type resolution below already answers with the single
3829            // type, or with its own ambiguity verdict; the argument count adds
3830            // nothing to that decision (#1812).
3831            return match type_resolution {
3832                LexicalTypeResolution::Resolved { unit, .. } => {
3833                    BareCallTargetResolution::Type(unit)
3834                }
3835                LexicalTypeResolution::Ambiguous => BareCallTargetResolution::Ambiguous,
3836                LexicalTypeResolution::Missing => BareCallTargetResolution::Missing,
3837            };
3838        }
3839    }
3840    // Every lookup tier is exhausted: no callable and no type candidate was
3841    // found. Reporting that as `Ambiguous` claimed an ambiguity between nothing
3842    // at all, and its early return in get_definition preempted the same-file
3843    // macro fallback - so a call to a macro defined in the referencing file
3844    // (libyang's `RBN_RIGHT`, glpk's `#define error dmx_error`) could never
3845    // resolve once an unresolvable include made the argument count unknown.
3846    // A no-candidate outcome is Missing, which is what makes the fallback
3847    // reachable (#1812).
3848    match type_resolution {
3849        LexicalTypeResolution::Resolved { unit, .. } => BareCallTargetResolution::Type(unit),
3850        LexicalTypeResolution::Ambiguous => BareCallTargetResolution::Ambiguous,
3851        LexicalTypeResolution::Missing => BareCallTargetResolution::Missing,
3852    }
3853}
3854
3855fn static_qualifier_type_scopes<'tree>(
3856    node: Node<'tree>,
3857    ctx: &ScanCtx<'_>,
3858) -> Option<Vec<Node<'tree>>> {
3859    if !matches!(
3860        node.kind(),
3861        "qualified_identifier" | "scoped_type_identifier"
3862    ) {
3863        return None;
3864    }
3865    // `maybe_record_type_hit` rejects nested type nodes before this helper, so
3866    // this root contains every structured component needed for prefix lookup.
3867    debug_assert!(!is_nested_type_node(node));
3868    let qualified = qualified_owner_components(node, ctx.source)?;
3869    static_qualifier_type_scopes_for_components(node, qualified, ctx)
3870}
3871
3872fn static_qualifier_type_scopes_for_components<'tree>(
3873    node: Node<'tree>,
3874    qualified: QualifiedOwnerComponents<'tree>,
3875    ctx: &ScanCtx<'_>,
3876) -> Option<Vec<Node<'tree>>> {
3877    if !qualified.global
3878        && qualified.names.first().is_some_and(|name| {
3879            name == ctx.spec.target.identifier()
3880                && qualified
3881                    .nodes
3882                    .first()
3883                    .is_some_and(|owner| local_type_name_shadows(*owner, ctx))
3884        })
3885    {
3886        return None;
3887    }
3888    let mut matches = Vec::new();
3889    let mut inherited_injected_name_is_shadowed = false;
3890    for component_count in 1..=qualified.names.len() {
3891        let resolution = resolve_type_components_lexically_at_for_target_with_scope_cache(
3892            node,
3893            &qualified.names[..component_count],
3894            qualified.global,
3895            &ctx.analyzer,
3896            ctx.visibility,
3897            &ctx.ordinary_type_imports,
3898            ctx.file,
3899            ctx.source,
3900            &ctx.spec.target,
3901            false,
3902            Some(&ctx.lexical_scope_cache),
3903        );
3904        match resolution {
3905            LexicalTypeResolution::Resolved {
3906                unit, candidates, ..
3907            } if (!ctx
3908                .analyzer
3909                .type_alias_provider()
3910                .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
3911                || ctx.visibility.external_type_candidate_visible_in_context(
3912                    &ctx.analyzer,
3913                    ctx.file,
3914                    &ctx.spec.target,
3915                    node,
3916                ))
3917                && (same_visible_symbol(&unit, &ctx.spec.target)
3918                    || candidates
3919                        .iter()
3920                        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target)))
3921                && target_alias_candidates_visible(&candidates, node, ctx) =>
3922            {
3923                let matched =
3924                    qualified_type_component_hit_node(qualified.nodes[component_count - 1], node);
3925                if !template_type_component_preserves_target(matched, &candidates, ctx) {
3926                    continue;
3927                }
3928                if !matches.iter().any(|existing: &Node<'_>| {
3929                    existing.start_byte() == matched.start_byte()
3930                        && existing.end_byte() == matched.end_byte()
3931                }) {
3932                    matches.push(matched);
3933                }
3934            }
3935            // The ordinary lexical resolver can remain ambiguous when the
3936            // qualified terminal is an alias whose canonical target is not
3937            // indexed (for example, `Hash::Digest` aliases an external
3938            // `std::array`). The target-guided path below still requires one
3939            // physically visible logical class for every emitted prefix.
3940            LexicalTypeResolution::Ambiguous => {
3941                return (!inherited_injected_name_is_shadowed)
3942                    .then(|| inherited_injected_class_qualifier_scope(node, ctx))
3943                    .flatten()
3944                    .map(|scope| vec![scope])
3945                    .or_else(|| target_guided_qualifier_type_scopes(node, ctx));
3946            }
3947            LexicalTypeResolution::Resolved { .. } => {
3948                if let Some(matched) =
3949                    target_guided_nested_alias_type_scope(node, &qualified, component_count, ctx)
3950                {
3951                    matches.push(matched);
3952                }
3953                inherited_injected_name_is_shadowed |= component_count == 1;
3954            }
3955            LexicalTypeResolution::Missing => {
3956                if let Some(matched) =
3957                    target_guided_nested_alias_type_scope(node, &qualified, component_count, ctx)
3958                {
3959                    matches.push(matched);
3960                }
3961            }
3962        }
3963    }
3964    if matches.is_empty() {
3965        (!inherited_injected_name_is_shadowed)
3966            .then(|| inherited_injected_class_qualifier_scope(node, ctx))
3967            .flatten()
3968            .map(|scope| vec![scope])
3969            .or_else(|| target_guided_qualifier_type_scopes(node, ctx))
3970    } else {
3971        Some(matches)
3972    }
3973}
3974
3975/// Recover a class owner in a qualified expression when guard-aware lookup
3976/// cannot prove the owner. Keep the hit on the owner component, not the member.
3977enum TargetGuidedQualifiedValueOwnerHit<'tree> {
3978    Proven(Node<'tree>),
3979    Unproven(Node<'tree>),
3980}
3981
3982fn target_guided_qualified_value_owner_hit<'tree>(
3983    node: Node<'tree>,
3984    ctx: &ScanCtx<'_>,
3985) -> Option<TargetGuidedQualifiedValueOwnerHit<'tree>> {
3986    let target = physically_visible_type_target(ctx)?;
3987    if !target.is_class() {
3988        return None;
3989    }
3990    let qualified = qualified_owner_components(node, ctx.source)?;
3991    let lexical_scope = match enclosing_lexical_scope_components(
3992        node,
3993        &ctx.analyzer,
3994        ctx.visibility,
3995        ctx.file,
3996        ctx.source,
3997    ) {
3998        LexicalScopeResolution::Resolved(scope) => scope,
3999        LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => {
4000            enclosing_namespace_components(node, ctx.source)
4001        }
4002    };
4003    let LexicalTypeResolution::Resolved {
4004        unit, candidates, ..
4005    } = ctx.visibility.resolve_type_components_lexically_for_target(
4006        &ctx.analyzer,
4007        ctx.file,
4008        &qualified.names,
4009        qualified.global,
4010        &lexical_scope,
4011        target,
4012    )
4013    else {
4014        return None;
4015    };
4016    let scope = qualified.nodes.last().copied()?;
4017    // Lexical component lookup does not consider source order, so it can
4018    // select a declaration that follows the reference. The forward selection
4019    // proves the owner only when that declaration is visible at the reference.
4020    let forward_uniquely_selects_target = match ctx
4021        .visibility
4022        .resolve_type_components_lexically_for_forward(
4023            &ctx.analyzer,
4024            ctx.file,
4025            &qualified.names,
4026            qualified.global,
4027            &lexical_scope,
4028        ) {
4029        LexicalTypeResolution::Resolved {
4030            unit, candidates, ..
4031        } if candidates.len() == 1 => {
4032            same_visible_symbol(&canonical_alias_target(&unit, ctx), target)
4033                && same_visible_symbol(&canonical_alias_target(&candidates[0], ctx), target)
4034                && ctx.visibility.external_type_candidate_visible_in_context(
4035                    &ctx.analyzer,
4036                    ctx.file,
4037                    &candidates[0],
4038                    scope,
4039                )
4040        }
4041        LexicalTypeResolution::Resolved { .. }
4042        | LexicalTypeResolution::Ambiguous
4043        | LexicalTypeResolution::Missing => false,
4044    };
4045    if forward_uniquely_selects_target
4046        || (same_visible_symbol(&unit, target)
4047            && !candidates.is_empty()
4048            && candidates
4049                .iter()
4050                .all(|candidate| same_visible_symbol(candidate, target)))
4051    {
4052        Some(TargetGuidedQualifiedValueOwnerHit::Proven(scope))
4053    } else if candidates
4054        .iter()
4055        .any(|candidate| same_visible_symbol(candidate, target))
4056    {
4057        Some(TargetGuidedQualifiedValueOwnerHit::Unproven(scope))
4058    } else {
4059        None
4060    }
4061}
4062
4063/// Resolve a nested class-owned alias when the indexed alias path is not a
4064/// standalone type candidate. The C++ index stores `basic_json::type_error`
4065/// as a synthetic child of `basic_json`, while source can qualify it through
4066/// a class alias such as `json::type_error`. Resolve the owner prefix first,
4067/// then canonicalize the structured member alias against the requested type.
4068fn target_guided_nested_alias_type_scope<'tree>(
4069    node: Node<'tree>,
4070    qualified: &QualifiedOwnerComponents<'tree>,
4071    component_count: usize,
4072    ctx: &ScanCtx<'_>,
4073) -> Option<Node<'tree>> {
4074    if component_count < 2 {
4075        return None;
4076    }
4077    let (owner_components, member_name) =
4078        qualified.names[..component_count].split_at(component_count - 1);
4079    let LexicalTypeResolution::Resolved { unit: owner, .. } = resolve_type_components_lexically_at(
4080        node,
4081        owner_components,
4082        qualified.global,
4083        &ctx.analyzer,
4084        ctx.visibility,
4085        &ctx.ordinary_type_imports,
4086        ctx.file,
4087        ctx.source,
4088    ) else {
4089        return None;
4090    };
4091    let member_name = member_name.first()?;
4092    let alias_provider = ctx.analyzer.type_alias_provider()?;
4093    ctx.visibility
4094        .visible_members_for_owner_name(ctx.file, &owner, member_name)
4095        .into_iter()
4096        .filter(|member| alias_provider.is_type_alias(member))
4097        .find(|member| {
4098            let member_visible = ctx.visibility.external_type_candidate_visible_in_context(
4099                &ctx.analyzer,
4100                ctx.file,
4101                member,
4102                node,
4103            ) || ctx
4104                .visibility
4105                .external_type_candidate_guard_compatible_in_context(
4106                    &ctx.analyzer,
4107                    ctx.file,
4108                    member,
4109                    node,
4110                );
4111            if !member_visible {
4112                return false;
4113            }
4114            same_visible_symbol(member, &ctx.spec.target)
4115                || same_visible_symbol(&canonical_alias_target(member, ctx), &ctx.spec.target)
4116        })
4117        .map(|_| qualified_type_component_hit_node(qualified.nodes[component_count - 1], node))
4118}
4119
4120fn canonical_alias_target(candidate: &CodeUnit, ctx: &ScanCtx<'_>) -> CodeUnit {
4121    if ctx.visibility.structured_class_alias_resolves_to_target(
4122        &ctx.analyzer,
4123        ctx.file,
4124        candidate,
4125        &ctx.spec.target,
4126    ) {
4127        return ctx.spec.target.clone();
4128    }
4129    let structured = ctx
4130        .visibility
4131        .canonical_type_unit(&ctx.analyzer, ctx.file, candidate);
4132    if let Some(canonical) = structured
4133        .as_ref()
4134        .filter(|canonical| !same_visible_symbol(canonical, candidate))
4135    {
4136        return canonical.clone();
4137    }
4138    structured.unwrap_or_else(|| candidate.clone())
4139}
4140
4141/// Preserve the alias component of a qualified reference when the alias target
4142/// is a dependent nested type and forward lookup retains its primary template
4143/// as the bounded identity.
4144fn class_alias_guard_compatible(candidate: &CodeUnit, node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
4145    ctx.visibility
4146        .external_type_candidate_guard_compatible_in_context(
4147            &ctx.analyzer,
4148            ctx.file,
4149            candidate,
4150            node,
4151        )
4152}
4153
4154fn visible_class_alias_candidate(candidate: &CodeUnit, node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
4155    ctx.visibility.is_physically_visible(ctx.file, candidate)
4156        && class_alias_guard_compatible(candidate, node, ctx)
4157}
4158
4159fn class_alias_path_preserves_target(
4160    candidate: &CodeUnit,
4161    target: &CodeUnit,
4162    ctx: &ScanCtx<'_>,
4163) -> bool {
4164    ctx.visibility.structured_class_alias_path_preserves_target(
4165        &ctx.analyzer,
4166        ctx.file,
4167        candidate,
4168        target,
4169    )
4170}
4171
4172fn target_guided_dependent_alias_qualifier_scope<'tree>(
4173    node: Node<'tree>,
4174    ctx: &ScanCtx<'_>,
4175) -> Option<Node<'tree>> {
4176    if !matches!(
4177        node.kind(),
4178        "qualified_identifier" | "scoped_type_identifier"
4179    ) {
4180        return None;
4181    }
4182    let target = physically_visible_type_target(ctx)?;
4183    let alias_provider = ctx.analyzer.type_alias_provider()?;
4184    if !target.is_class() || alias_provider.is_type_alias(target) {
4185        return None;
4186    }
4187    let nodes = cpp_name_component_nodes(node)?;
4188    let names = nodes
4189        .iter()
4190        .map(|component| node_text(*component, ctx.source).to_string())
4191        .collect::<Vec<_>>();
4192    let global = is_globally_qualified_cpp_name(node);
4193    let lexical_scope = match enclosing_lexical_scope_components(
4194        node,
4195        &ctx.analyzer,
4196        ctx.visibility,
4197        ctx.file,
4198        ctx.source,
4199    ) {
4200        LexicalScopeResolution::Resolved(scope) => scope,
4201        LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => {
4202            enclosing_namespace_components(node, ctx.source)
4203        }
4204    };
4205    for component_count in 1..=names.len() {
4206        let components = &names[..component_count];
4207        let name = components.last()?;
4208        let candidates = ctx
4209            .visibility
4210            .visible_identifier_candidates(ctx.file, name)
4211            .filter(|candidate| alias_provider.is_type_alias(candidate))
4212            .filter(|candidate| visible_class_alias_candidate(candidate, node, ctx))
4213            .filter(|candidate| {
4214                let candidate_components = canonical_cpp_scope_components(candidate);
4215                lexical_component_tiers(components, global, &lexical_scope)
4216                    .any(|tier| tier == candidate_components)
4217                    || (component_count == 1
4218                        && member_alias_owner_matches_reference_for(
4219                            candidate,
4220                            nodes[component_count - 1],
4221                            ctx,
4222                        ))
4223            })
4224            .filter(|candidate| class_alias_path_preserves_target(candidate, target, ctx));
4225        let mut aliases: Vec<&CodeUnit> = Vec::new();
4226        for candidate in candidates {
4227            if !aliases
4228                .iter()
4229                .any(|existing| same_logical_symbol(existing, candidate))
4230            {
4231                aliases.push(candidate);
4232            }
4233        }
4234        if aliases.len() == 1 {
4235            return nodes.get(component_count - 1).copied();
4236        }
4237        if aliases.len() > 1 {
4238            return None;
4239        }
4240    }
4241    None
4242}
4243
4244/// Preserve an unqualified class-owned alias when its dependent target path
4245/// retains the requested primary template as the bounded forward identity.
4246fn target_guided_dependent_class_alias_leaf<'tree>(
4247    node: Node<'tree>,
4248    ctx: &ScanCtx<'_>,
4249) -> Option<Node<'tree>> {
4250    if node.kind() != "type_identifier"
4251        || is_declaration_name(node)
4252        || local_type_name_shadows(node, ctx)
4253    {
4254        return None;
4255    }
4256    let target = physically_visible_type_target(ctx)?;
4257    let alias_provider = ctx.analyzer.type_alias_provider()?;
4258    if !target.is_class() || alias_provider.is_type_alias(target) {
4259        return None;
4260    }
4261    let name = node_text(node, ctx.source);
4262    let aliases = ctx
4263        .visibility
4264        .visible_identifier_candidates(ctx.file, name)
4265        .filter(|candidate| alias_provider.is_type_alias(candidate))
4266        .filter(|candidate| member_alias_owner_matches_reference_for(candidate, node, ctx))
4267        .filter(|candidate| visible_class_alias_candidate(candidate, node, ctx))
4268        .filter(|candidate| class_alias_path_preserves_target(candidate, target, ctx))
4269        .collect::<Vec<_>>();
4270    matches!(aliases.as_slice(), [_]).then_some(node)
4271}
4272
4273/// Recover a namespace alias whose guard state blocks ordinary visibility.
4274/// Require one visible canonical target and an exact structured alias path.
4275fn target_guided_unproven_alias_type_reference<'tree>(
4276    node: Node<'tree>,
4277    candidates: &[CodeUnit],
4278    ctx: &ScanCtx<'_>,
4279) -> Option<Node<'tree>> {
4280    let template_arguments = cpp_template_reference_arguments(node, ctx.source);
4281    let target = physically_visible_type_target(ctx)?;
4282    if !target.is_class() {
4283        return None;
4284    }
4285    let alias_provider = ctx.analyzer.type_alias_provider()?;
4286    let (components, _) = type_reference_components(node, ctx.source)?;
4287    let hit = template_arguments
4288        .as_ref()
4289        .and_then(|_| template_reference_name_node(node))
4290        .map(function_terminal_node)
4291        .unwrap_or_else(|| function_terminal_node(node));
4292    candidates
4293        .iter()
4294        .filter(|candidate| {
4295            alias_provider.is_type_alias(candidate)
4296                && ctx.visibility.is_physically_visible(ctx.file, candidate)
4297                && canonical_cpp_scope_components(candidate) == components
4298        })
4299        .find(|candidate| {
4300            template_arguments.as_ref().map_or_else(
4301                || {
4302                    same_visible_symbol(&canonical_alias_target(candidate, ctx), target)
4303                        || ctx.visibility.structured_alias_primary_preserves_target(
4304                            &ctx.analyzer,
4305                            ctx.file,
4306                            candidate,
4307                            target,
4308                        )
4309                },
4310                |arguments| {
4311                    ctx.visibility.template_alias_arguments_preserve_target(
4312                        &ctx.analyzer,
4313                        ctx.file,
4314                        candidate,
4315                        arguments,
4316                        target,
4317                    )
4318                },
4319            )
4320        })
4321        .map(|_| hit)
4322}
4323
4324fn target_alias_candidates_visible(
4325    candidates: &[CodeUnit],
4326    reference: Node<'_>,
4327    ctx: &ScanCtx<'_>,
4328) -> bool {
4329    let Some(alias_provider) = ctx.analyzer.type_alias_provider() else {
4330        return true;
4331    };
4332    if candidates.iter().any(|candidate| {
4333        !alias_provider.is_type_alias(candidate)
4334            && ctx.visibility.same_template_member_identity(
4335                &ctx.analyzer,
4336                candidate,
4337                &ctx.spec.target,
4338            )
4339    }) {
4340        return true;
4341    }
4342    let target_aliases = candidates
4343        .iter()
4344        .filter(|candidate| {
4345            alias_provider.is_type_alias(candidate)
4346                && same_visible_symbol(&canonical_alias_target(candidate, ctx), &ctx.spec.target)
4347        })
4348        .collect::<Vec<_>>();
4349    target_aliases.is_empty()
4350        || target_aliases
4351            .iter()
4352            .any(|candidate| type_candidate_visible_at_reference(candidate, reference, ctx))
4353}
4354
4355fn type_candidate_visible_at_reference(
4356    candidate: &CodeUnit,
4357    reference: Node<'_>,
4358    ctx: &ScanCtx<'_>,
4359) -> bool {
4360    let class_owned_alias = ctx
4361        .analyzer
4362        .type_alias_provider()
4363        .is_some_and(|provider| provider.is_type_alias(candidate))
4364        && ctx
4365            .analyzer
4366            .parent_of(candidate)
4367            .is_some_and(|owner| owner.is_class());
4368    if class_owned_alias {
4369        let conditional_family = ctx
4370            .visibility
4371            .is_exhaustive_same_fqn_type_declaration_family(&ctx.analyzer, ctx.file, candidate);
4372        let owner_match = qualified_reference_selects_type_candidate(candidate, reference, ctx)
4373            || unqualified_reference_selects_inherited_alias(candidate, reference, ctx)
4374            || member_alias_owner_matches_reference_for(candidate, reference, ctx);
4375        let guard_match = ctx
4376            .visibility
4377            .external_type_candidate_guard_compatible_in_context(
4378                &ctx.analyzer,
4379                ctx.file,
4380                candidate,
4381                reference,
4382            );
4383        let general_match = conditional_family
4384            && ctx.visibility.external_type_candidate_visible_in_context(
4385                &ctx.analyzer,
4386                ctx.file,
4387                candidate,
4388                reference,
4389            );
4390        return owner_match && (guard_match || general_match);
4391    }
4392    ctx.visibility.external_type_candidate_visible_in_context(
4393        &ctx.analyzer,
4394        ctx.file,
4395        candidate,
4396        reference,
4397    )
4398}
4399
4400fn unqualified_reference_selects_inherited_alias(
4401    candidate: &CodeUnit,
4402    reference: Node<'_>,
4403    ctx: &ScanCtx<'_>,
4404) -> bool {
4405    let Some((components, global)) = type_reference_components(reference, ctx.source) else {
4406        return false;
4407    };
4408    if global || components.len() != 1 {
4409        return false;
4410    }
4411    matches!(
4412        resolve_type_node_lexically_for_target(
4413            reference,
4414            &ctx.analyzer,
4415            ctx.visibility,
4416            &ctx.ordinary_type_imports,
4417            ctx.file,
4418            ctx.source,
4419            candidate,
4420            Some(&ctx.lexical_scope_cache),
4421            ctx.recovered_sentinel_scope(reference).as_deref(),
4422        ),
4423        LexicalTypeResolution::Resolved {
4424            ref unit,
4425            ref candidates,
4426            ..
4427        } if ctx
4428            .visibility
4429            .same_template_member_identity(&ctx.analyzer, unit, candidate)
4430            || candidates.iter().any(|resolved| {
4431                ctx.visibility.same_template_member_identity(
4432                    &ctx.analyzer,
4433                    resolved,
4434                    candidate,
4435                )
4436            })
4437    )
4438}
4439
4440fn qualified_reference_selects_type_candidate(
4441    candidate: &CodeUnit,
4442    reference: Node<'_>,
4443    ctx: &ScanCtx<'_>,
4444) -> bool {
4445    let Some((components, global)) = type_reference_components(reference, ctx.source) else {
4446        return false;
4447    };
4448    if components.len() < 2 {
4449        return false;
4450    }
4451    let candidate_components = canonical_cpp_scope_components(candidate);
4452    let lexical_scope = ctx.recovered_sentinel_scope(reference).unwrap_or_else(|| {
4453        match enclosing_lexical_scope_components(
4454            reference,
4455            &ctx.analyzer,
4456            ctx.visibility,
4457            ctx.file,
4458            ctx.source,
4459        ) {
4460            LexicalScopeResolution::Resolved(scope) => scope,
4461            LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => {
4462                enclosing_namespace_components(reference, ctx.source)
4463            }
4464        }
4465    });
4466    lexical_component_tiers(&components, global, &lexical_scope)
4467        .any(|qualified| qualified == candidate_components)
4468}
4469
4470fn qualified_type_component_hit_node<'tree>(
4471    component: Node<'tree>,
4472    qualified: Node<'tree>,
4473) -> Node<'tree> {
4474    let mut current = component;
4475    while let Some(parent) = current.parent() {
4476        let is_type_name = matches!(
4477            parent.kind(),
4478            "template_type"
4479                | "qualified_identifier"
4480                | "scoped_identifier"
4481                | "scoped_type_identifier"
4482        ) && parent
4483            .child_by_field_name("name")
4484            .is_some_and(|name| same_node(name, current));
4485        if !is_type_name {
4486            break;
4487        }
4488        current = parent;
4489        if same_node(parent, qualified) {
4490            break;
4491        }
4492    }
4493    current
4494}
4495
4496fn template_type_component_preserves_target(
4497    node: Node<'_>,
4498    candidates: &[CodeUnit],
4499    ctx: &ScanCtx<'_>,
4500) -> bool {
4501    template_reference_candidates_select_target(
4502        node,
4503        candidates,
4504        &ctx.analyzer,
4505        ctx.visibility,
4506        ctx.file,
4507        ctx.source,
4508        &ctx.spec.target,
4509    )
4510}
4511
4512fn template_reference_candidates_select_target(
4513    node: Node<'_>,
4514    candidates: &[CodeUnit],
4515    analyzer: &CppGraphSource<'_>,
4516    visibility: &VisibilityIndex<'_>,
4517    file: &ProjectFile,
4518    source: &str,
4519    target: &CodeUnit,
4520) -> bool {
4521    let Some(arguments) = cpp_template_reference_arguments(node, source) else {
4522        return !visibility.is_template_specialization(target);
4523    };
4524    let direct_template_name =
4525        template_reference_name_node(node).map(|name| node_text(name, source));
4526    let named_alias_selects_target = direct_template_name.is_some_and(|name| {
4527        analyzer.type_alias_provider().is_some_and(|provider| {
4528            visibility
4529                .visible_identifier_candidates(file, name)
4530                .filter(|candidate| provider.is_type_alias(candidate))
4531                .any(|candidate| {
4532                    visibility.template_alias_arguments_preserve_target(
4533                        analyzer, file, candidate, &arguments, target,
4534                    )
4535                })
4536        })
4537    });
4538    named_alias_selects_target
4539        || candidates.iter().any(|candidate| {
4540            (same_visible_symbol(candidate, target)
4541                && visibility.is_primary_template(target)
4542                && direct_template_name == Some(candidate.identifier()))
4543                || visibility.template_alias_arguments_preserve_target(
4544                    analyzer, file, candidate, &arguments, target,
4545                )
4546                || visibility
4547                    .resolve_template_arguments(file, candidate.clone(), &arguments)
4548                    .is_ok_and(|resolved| same_visible_symbol(&resolved, target))
4549        })
4550}
4551
4552fn template_reference_name_node(node: Node<'_>) -> Option<Node<'_>> {
4553    let template = if node.kind() == "template_type" {
4554        node
4555    } else {
4556        node.child_by_field_name("name")
4557            .filter(|name| name.kind() == "template_type")?
4558    };
4559    template.child_by_field_name("name")
4560}
4561
4562fn type_resolution_matches_target(
4563    node: Node<'_>,
4564    unit: &CodeUnit,
4565    candidates: &[CodeUnit],
4566    ctx: &ScanCtx<'_>,
4567) -> bool {
4568    type_resolution_matches_unit_target(node, unit, candidates, &ctx.spec.target, ctx)
4569}
4570
4571fn type_resolution_matches_unit_target(
4572    node: Node<'_>,
4573    unit: &CodeUnit,
4574    candidates: &[CodeUnit],
4575    target: &CodeUnit,
4576    ctx: &ScanCtx<'_>,
4577) -> bool {
4578    target_alias_candidates_visible(candidates, node, ctx)
4579        && type_resolution_identifies_unit_target(node, unit, candidates, target, ctx)
4580}
4581
4582/// The identity half of the type-resolution match, without the alias
4583/// visibility gate.
4584///
4585/// Use it only on the without-visibility fallback path, which reports an
4586/// unproven hit. An alias spelling does not contain the target identifier, so
4587/// the name-mention fallback can never recover a rejected alias reference: the
4588/// site would disappear instead of degrading to a reviewable hit.
4589fn type_resolution_identifies_unit_target(
4590    node: Node<'_>,
4591    unit: &CodeUnit,
4592    candidates: &[CodeUnit],
4593    target: &CodeUnit,
4594    ctx: &ScanCtx<'_>,
4595) -> bool {
4596    if !template_alias_owner_matches_reference(node, target, ctx) {
4597        return false;
4598    }
4599    if ctx.visibility.is_template_specialization(target)
4600        && cpp_template_reference_arguments(node, ctx.source).is_some()
4601    {
4602        let selected_unit =
4603            cpp_template_reference_arguments(node, ctx.source).and_then(|arguments| {
4604                ctx.visibility
4605                    .resolve_template_arguments(ctx.file, unit.clone(), &arguments)
4606                    .ok()
4607            });
4608        return selected_unit
4609            .as_ref()
4610            .is_some_and(|selected| same_visible_symbol(selected, target))
4611            || template_reference_candidates_select_target(
4612                node,
4613                candidates,
4614                &ctx.analyzer,
4615                ctx.visibility,
4616                ctx.file,
4617                ctx.source,
4618                target,
4619            );
4620    }
4621    unit == target
4622        || ctx
4623            .visibility
4624            .same_template_member_identity(&ctx.analyzer, unit, target)
4625        || ctx.visibility.c_tag_declaration_family_matches_target(
4626            &ctx.analyzer,
4627            ctx.file,
4628            &candidates.iter().collect::<Vec<_>>(),
4629            target,
4630        )
4631        || ctx.visibility.structured_class_alias_resolves_to_target(
4632            &ctx.analyzer,
4633            ctx.file,
4634            unit,
4635            target,
4636        )
4637        || candidates.iter().any(|candidate| {
4638            ctx.visibility
4639                .same_template_member_identity(&ctx.analyzer, candidate, target)
4640                || ctx.visibility.structured_class_alias_resolves_to_target(
4641                    &ctx.analyzer,
4642                    ctx.file,
4643                    candidate,
4644                    target,
4645                )
4646        })
4647}
4648
4649/// Keep a member alias attached to the class specialization that declares it.
4650/// A target-guided lexical lookup can otherwise retain the primary alias when
4651/// the source reference is inside a partial specialization with the same
4652/// unqualified alias name. Compare the indexed template identities instead of
4653/// rendered text or suffixes.
4654fn template_alias_owner_matches_reference(
4655    node: Node<'_>,
4656    target: &CodeUnit,
4657    ctx: &ScanCtx<'_>,
4658) -> bool {
4659    if !ctx
4660        .analyzer
4661        .type_alias_provider()
4662        .is_some_and(|provider| provider.is_type_alias(target))
4663    {
4664        return true;
4665    }
4666    let Some(target_owner) = ctx.analyzer.parent_of(target) else {
4667        return true;
4668    };
4669    if !target_owner.is_class() {
4670        return true;
4671    }
4672    let Some(reference_owner) = structured_enclosing_owner(node, ctx) else {
4673        return true;
4674    };
4675    if !ctx.visibility.is_template_specialization(&target_owner)
4676        && !ctx.visibility.is_template_specialization(&reference_owner)
4677    {
4678        return true;
4679    }
4680    same_visible_symbol(&target_owner, &reference_owner)
4681}
4682
4683fn inherited_injected_class_qualifier_scope<'tree>(
4684    node: Node<'tree>,
4685    ctx: &ScanCtx<'_>,
4686) -> Option<Node<'tree>> {
4687    let qualified = qualified_owner_components(node, ctx.source)?;
4688    if qualified.global || qualified.names.is_empty() {
4689        return None;
4690    }
4691    let injected_name = &qualified.names[0];
4692    if !ctx.spec.target.is_class()
4693        || ctx.spec.target.identifier() != injected_name
4694        || physically_visible_type_target(ctx).is_none()
4695    {
4696        return None;
4697    }
4698    let enclosing_owner = structured_enclosing_owner(node, ctx)?;
4699    let owner = ctx.visibility.inherited_injected_class_owner(
4700        &ctx.analyzer,
4701        ctx.file,
4702        &enclosing_owner,
4703        injected_name,
4704    )?;
4705    same_visible_symbol(&owner, &ctx.spec.target)
4706        .then(|| qualified.nodes.first().copied())
4707        .flatten()
4708}
4709
4710/// Resolve each qualified type component against the inverse target while
4711/// preserving C++ lexical-tier precedence and structured alias identity.
4712fn target_guided_qualifier_type_scopes<'tree>(
4713    node: Node<'tree>,
4714    ctx: &ScanCtx<'_>,
4715) -> Option<Vec<Node<'tree>>> {
4716    if !matches!(
4717        node.kind(),
4718        "qualified_identifier" | "scoped_type_identifier"
4719    ) {
4720        return None;
4721    }
4722    let target = physically_visible_type_target(ctx)?;
4723    let qualified = qualified_owner_components(node, ctx.source)?;
4724    // Prefer the C++ lexical tier that exactly matches a candidate's indexed
4725    // scope before falling back to suffix recovery.  A short unqualified
4726    // owner can have a same-spelled class in a nested namespace (for example
4727    // `ThreadDetails` and `Ui::ThreadDetails`).  Suffix-only matching treats
4728    // both as possible owners and then fails closed, even though the
4729    // translation unit's lexical scope selects the global class.  Keep the
4730    // suffix path for malformed namespace sentinels, where the parser does
4731    // not expose every indexed scope component.
4732    let lexical_scope = match enclosing_lexical_scope_components(
4733        node,
4734        &ctx.analyzer,
4735        ctx.visibility,
4736        ctx.file,
4737        ctx.source,
4738    ) {
4739        LexicalScopeResolution::Resolved(scope) => scope,
4740        LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => {
4741            enclosing_namespace_components(node, ctx.source)
4742        }
4743    };
4744    let indexed_owner_scope =
4745        indexed_enclosing_owner_scope(&ctx.analyzer, ctx.visibility, ctx.file, node);
4746    let recovered_owner_scope = ctx.recovered_sentinel_scope(node);
4747    let mut matches = Vec::new();
4748    for component_count in 1..=qualified.names.len() {
4749        let components = &qualified.names[..component_count];
4750        let lexical_tiers = lexical_component_tiers(components, qualified.global, &lexical_scope)
4751            .collect::<Vec<_>>();
4752        let name = components.last()?;
4753        let mut candidates = Vec::new();
4754        let mut exact_candidates = Vec::new();
4755        for candidate in ctx
4756            .visibility
4757            .visible_identifier_candidates(ctx.file, name)
4758            .filter(|candidate| candidate.is_class())
4759            .filter(|candidate| type_candidate_visible_at_reference(candidate, node, ctx))
4760        {
4761            let candidate_components = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
4762                brokk_bifrost_core::analyzer::Language::Cpp,
4763                &cpp_name_for(candidate),
4764            );
4765            if !candidate_components.ends_with(components)
4766                || candidates
4767                    .iter()
4768                    .any(|existing| same_logical_symbol(existing, candidate))
4769            {
4770                continue;
4771            }
4772            let exact_lexical_scope = lexical_tiers
4773                .iter()
4774                .any(|expected| expected == &candidate_components);
4775            let candidate_owner = &candidate_components[..candidate_components.len() - 1];
4776            let structured_owner_match = indexed_owner_scope
4777                .as_ref()
4778                .is_some_and(|owner| owner.starts_with(candidate_owner))
4779                || recovered_owner_scope
4780                    .as_ref()
4781                    .is_some_and(|owner| owner.starts_with(candidate_owner));
4782            let class_alias_owner_match = ctx
4783                .analyzer
4784                .type_alias_provider()
4785                .is_some_and(|provider| provider.is_type_alias(candidate))
4786                && member_alias_owner_matches_reference_for(candidate, node, ctx);
4787            let macro_namespace_owner_match = is_declaration_name(node)
4788                && macro_namespace_scope_matches(candidate_owner, node, ctx);
4789            if components.len() == 1
4790                && candidate_components != components
4791                && !exact_lexical_scope
4792                && !structured_owner_match
4793                && !class_alias_owner_match
4794                && !macro_namespace_owner_match
4795            {
4796                continue;
4797            }
4798            candidates.push(candidate.clone());
4799            if exact_lexical_scope {
4800                exact_candidates.push(candidate.clone());
4801            }
4802        }
4803        if !exact_candidates.is_empty() {
4804            candidates = exact_candidates;
4805        }
4806        // A typedef spelling can qualify nested C++ members while forward
4807        // lookup canonicalizes that spelling to its underlying class. Preserve
4808        // the exact alias prefix only when structured alias resolution proves
4809        // that it denotes this inverse target.
4810        let canonical_alias_target_matches = matches!(
4811            candidates.as_slice(),
4812            [candidate]
4813                if ctx
4814                    .analyzer
4815                    .type_alias_provider()
4816                    .is_some_and(|provider| provider.is_type_alias(candidate))
4817                    && type_candidate_visible_at_reference(candidate, node, ctx)
4818                    && same_visible_symbol(&canonical_alias_target(candidate, ctx), target)
4819                    && (brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
4820                        brokk_bifrost_core::analyzer::Language::Cpp,
4821                        &cpp_name_for(candidate),
4822                    ) == components
4823                        || member_alias_owner_matches_reference_for(candidate, node, ctx))
4824        );
4825        let direct_alias_target = ctx
4826            .analyzer
4827            .type_alias_provider()
4828            .is_some_and(|provider| provider.is_type_alias(target))
4829            && candidates
4830                .iter()
4831                .any(|candidate| same_symbol(candidate, target));
4832        let unique_target = matches!(
4833            candidates.as_slice(),
4834            [candidate] if same_visible_symbol(candidate, target)
4835        );
4836        if direct_alias_target || unique_target || canonical_alias_target_matches {
4837            let matched = if ctx
4838                .analyzer
4839                .type_alias_provider()
4840                .is_some_and(|provider| provider.is_type_alias(target))
4841                && ctx
4842                    .analyzer
4843                    .parent_of(target)
4844                    .is_some_and(|owner| owner.is_class())
4845                && ctx
4846                    .visibility
4847                    .is_exhaustive_same_fqn_type_declaration_family(&ctx.analyzer, ctx.file, target)
4848                && !class_owned_alias_has_distinct_visible_sibling(target, ctx)
4849            {
4850                // The alias declaration owns the terminal component. Keep
4851                // the inverse range narrow so `MathLib::bigint` records the
4852                // `bigint` token, not the complete qualified owner path.
4853                qualified.nodes[component_count - 1]
4854            } else {
4855                qualified_type_component_hit_node(qualified.nodes[component_count - 1], node)
4856            };
4857            if template_type_component_preserves_target(matched, &candidates, ctx) {
4858                matches.push(matched);
4859            }
4860        }
4861    }
4862    (!matches.is_empty()).then_some(matches)
4863}
4864
4865fn class_owned_alias_has_distinct_visible_sibling(target: &CodeUnit, ctx: &ScanCtx<'_>) -> bool {
4866    let Some(alias_provider) = ctx.analyzer.type_alias_provider() else {
4867        return false;
4868    };
4869    ctx.visibility
4870        .visible_identifier_candidates(ctx.file, target.identifier())
4871        .any(|candidate| {
4872            alias_provider.is_type_alias(candidate)
4873                && candidate.identifier() == target.identifier()
4874                && !same_visible_symbol(candidate, target)
4875                && ctx
4876                    .analyzer
4877                    .parent_of(candidate)
4878                    .is_some_and(|owner| owner.is_class())
4879        })
4880}
4881
4882/// Recover an out-of-line owner when the owner declaration and the reference
4883/// use different unknown preprocessor guards. Keep this result unproven.
4884fn target_guided_unproven_out_of_line_owner<'tree>(
4885    node: Node<'tree>,
4886    ctx: &ScanCtx<'_>,
4887) -> Option<Node<'tree>> {
4888    if !matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
4889        || !is_declaration_name(node)
4890    {
4891        return None;
4892    }
4893    let target = physically_visible_type_target(ctx)?;
4894    if !target.is_class() {
4895        return None;
4896    }
4897    let qualified = qualified_owner_components(node, ctx.source)?;
4898    let target_components = canonical_cpp_scope_components(target);
4899    let target_namespace = &target_components[..target_components.len().saturating_sub(1)];
4900    let parser_scope = enclosing_namespace_components(node, ctx.source);
4901    let mut scope = ctx.recovered_sentinel_scope(node).or_else(|| {
4902        if !parser_scope.is_empty() || target_namespace.is_empty() {
4903            Some(parser_scope)
4904        } else {
4905            indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)
4906        }
4907    })?;
4908    if has_malformed_wrapper_function_definition_ancestor(node)
4909        && target_namespace.starts_with(&scope)
4910        && target_namespace.len() > scope.len()
4911    {
4912        scope = target_namespace.to_vec();
4913    }
4914    if !lexical_component_tiers(&qualified.names, qualified.global, &scope)
4915        .any(|components| components == target_components)
4916    {
4917        return None;
4918    }
4919    let owner_name = qualified.names.last()?;
4920    let candidates = ctx
4921        .visibility
4922        .visible_identifier_candidates(ctx.file, owner_name)
4923        .filter(|candidate| {
4924            candidate.is_class() && canonical_cpp_scope_components(candidate) == target_components
4925        })
4926        .collect::<Vec<_>>();
4927    if candidates.is_empty()
4928        || candidates
4929            .iter()
4930            .any(|candidate| !same_visible_symbol(candidate, target))
4931    {
4932        return None;
4933    }
4934    qualified.nodes.last().copied()
4935}
4936
4937fn macro_namespace_scope_matches(
4938    candidate_owner: &[String],
4939    node: Node<'_>,
4940    ctx: &ScanCtx<'_>,
4941) -> bool {
4942    let namespace = enclosing_namespace_components(node, ctx.source);
4943    if namespace.is_empty() || candidate_owner.is_empty() {
4944        return false;
4945    }
4946    let mut expanded_owner = Vec::new();
4947    for component in candidate_owner {
4948        if let Some(replacement) =
4949            ctx.visibility
4950                .object_macro_replacement_at(ctx.file, component, node.start_byte())
4951        {
4952            let replacement_components =
4953                brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
4954                    brokk_bifrost_core::analyzer::Language::Cpp,
4955                    &replacement,
4956                );
4957            if replacement_components.is_empty() {
4958                return false;
4959            }
4960            expanded_owner.extend(replacement_components);
4961        } else {
4962            expanded_owner.push(component.clone());
4963        }
4964    }
4965    expanded_owner == namespace
4966}
4967
4968fn target_guided_missing_type_leaf<'tree>(
4969    node: Node<'tree>,
4970    ctx: &ScanCtx<'_>,
4971) -> Option<Node<'tree>> {
4972    physically_visible_type_target(ctx)?;
4973    target_guided_missing_dependent_nested_type_leaf(node, ctx)
4974        .or_else(|| target_guided_missing_declaration_type_leaf(node, ctx))
4975        .or_else(|| target_guided_missing_alias_rhs_type_leaf(node, ctx))
4976        .or_else(|| target_guided_missing_class_alias_target_type_leaf(node, ctx))
4977        .or_else(|| target_guided_missing_member_alias_type_leaf(node, ctx))
4978        .or_else(|| target_guided_missing_template_argument_type_leaf(node, ctx))
4979}
4980
4981/// Recover a bare class-owned alias whose structured canonical target is the
4982/// requested type. The class owner must enclose the reference, and every alias
4983/// with that spelling in the owner chain must preserve the same target.
4984fn target_guided_missing_class_alias_target_type_leaf<'tree>(
4985    node: Node<'tree>,
4986    ctx: &ScanCtx<'_>,
4987) -> Option<Node<'tree>> {
4988    if node.kind() != "type_identifier"
4989        || is_declaration_name(node)
4990        || local_type_name_shadows(node, ctx)
4991    {
4992        return None;
4993    }
4994    let alias_provider = ctx.analyzer.type_alias_provider()?;
4995    let name = node_text(node, ctx.source);
4996    let aliases = ctx
4997        .visibility
4998        .visible_identifier_candidates(ctx.file, name)
4999        .filter(|candidate| alias_provider.is_type_alias(candidate))
5000        .filter(|candidate| {
5001            ctx.analyzer
5002                .parent_of(candidate)
5003                .is_some_and(|owner| owner.is_class())
5004        })
5005        .filter(|candidate| member_alias_owner_matches_reference_for(candidate, node, ctx))
5006        .filter(|candidate| class_alias_guard_compatible(candidate, node, ctx))
5007        .collect::<Vec<_>>();
5008    (!aliases.is_empty()
5009        && aliases.iter().all(|candidate| {
5010            same_visible_symbol(&canonical_alias_target(candidate, ctx), &ctx.spec.target)
5011        }))
5012    .then_some(node)
5013}
5014
5015/// Recover an ambiguous unqualified alias used by a parameter or placement-new
5016/// type only when the indexed class owner proves the alias declaration. This
5017/// narrow path covers malformed class bodies without accepting unrelated aliases.
5018fn target_guided_ambiguous_owned_alias_type_leaf<'tree>(
5019    node: Node<'tree>,
5020    ctx: &ScanCtx<'_>,
5021) -> Option<Node<'tree>> {
5022    let parameter = nearest_declaration_type_context(node).is_some_and(|declaration| {
5023        matches!(
5024            declaration.kind(),
5025            "parameter_declaration" | "optional_parameter_declaration"
5026        )
5027    });
5028    let placement_new_type = ctx.ancestry.parent(node).is_some_and(|parent| {
5029        parent.kind() == "new_expression" && parent.child_by_field_name("type") == Some(node)
5030    });
5031    if !parameter && !placement_new_type {
5032        return None;
5033    }
5034    if !ctx
5035        .analyzer
5036        .type_alias_provider()
5037        .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
5038        || !type_alias_owner_matches_structured_reference(node, ctx)
5039    {
5040        return None;
5041    }
5042    target_guided_missing_declaration_type_leaf(node, ctx)
5043}
5044
5045/// Recover the terminal leaf of `Owner<T>::Nested` when a malformed namespace
5046/// sentinel prevents ordinary lexical resolution. The indexed target must have
5047/// an indexed class parent, the structured owner path must compose with one
5048/// proven lexical namespace source, and every visible candidate at that exact
5049/// owner path must be the indexed parent. This keeps the fallback owner-based;
5050/// a same-spelled nested type under another template remains unproven.
5051fn target_guided_missing_dependent_nested_type_leaf<'tree>(
5052    node: Node<'tree>,
5053    ctx: &ScanCtx<'_>,
5054) -> Option<Node<'tree>> {
5055    if !matches!(
5056        node.kind(),
5057        "qualified_identifier" | "scoped_type_identifier"
5058    ) || !qualified_type_scope_contains_template(node)
5059    {
5060        return None;
5061    }
5062    let name = node
5063        .child_by_field_name("name")
5064        .filter(|name| name.kind() == "type_identifier")?;
5065    if node_text(name, ctx.source) != ctx.spec.target.identifier() {
5066        return None;
5067    }
5068    let owner_target = ctx.analyzer.parent_of(&ctx.spec.target)?;
5069    if !owner_target.is_class() {
5070        return None;
5071    }
5072    let owner = node.child_by_field_name("scope")?;
5073    let owner_resolution = resolve_type_node_lexically_for_target(
5074        owner,
5075        &ctx.analyzer,
5076        ctx.visibility,
5077        &ctx.ordinary_type_imports,
5078        ctx.file,
5079        ctx.source,
5080        &owner_target,
5081        Some(&ctx.lexical_scope_cache),
5082        ctx.recovered_sentinel_scope(owner).as_deref(),
5083    );
5084    if matches!(
5085        owner_resolution,
5086        LexicalTypeResolution::Resolved {
5087            ref unit,
5088            ref candidates,
5089            ..
5090        } if type_resolution_matches_unit_target(
5091            owner,
5092            unit,
5093            candidates,
5094            &owner_target,
5095            ctx,
5096        )
5097    ) {
5098        return Some(name);
5099    }
5100
5101    let qualified = qualified_owner_components(node, ctx.source)?;
5102    let namespace = ctx
5103        .lexical_scope_cache
5104        .orphaned
5105        .enclosing_namespace_components(node, ctx.source);
5106    let indexed_scope = ctx
5107        .recovered_sentinel_scope(node)
5108        .or_else(|| (!namespace.is_empty()).then_some(namespace))
5109        .or_else(|| indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node))?;
5110    let owner_components = canonical_cpp_scope_components(&owner_target);
5111    if !lexical_component_tiers(&qualified.names, qualified.global, &indexed_scope)
5112        .any(|components| components == owner_components)
5113    {
5114        return None;
5115    }
5116    let scoped_candidates = visible_type_identifier_candidates(ctx, owner_target.identifier())
5117        .into_iter()
5118        .filter(|candidate| canonical_cpp_scope_components(candidate) == owner_components)
5119        .collect::<Vec<_>>();
5120    (!scoped_candidates.is_empty()
5121        && scoped_candidates
5122            .iter()
5123            .all(|candidate| same_visible_symbol(candidate, &owner_target)))
5124    .then_some(name)
5125}
5126
5127/// Recover a nested type-alias reference when parser recovery leaves an
5128/// unqualified template argument under a member function.  The ordinary
5129/// lexical lookup can select a same-spelled namespace alias (or fail closed)
5130/// even though the indexed callable owner proves that the reference is inside
5131/// the class which declares the target alias.
5132fn target_guided_missing_member_alias_type_leaf<'tree>(
5133    node: Node<'tree>,
5134    ctx: &ScanCtx<'_>,
5135) -> Option<Node<'tree>> {
5136    if !is_cpp_template_argument_type_leaf(node)
5137        || is_declaration_name(node)
5138        || ctx
5139            .target_declaration_ranges
5140            .iter()
5141            .any(|range| range.start_byte <= node.start_byte() && node.end_byte() <= range.end_byte)
5142        || node_text(node, ctx.source) != ctx.spec.target.identifier()
5143        || local_type_name_shadows(node, ctx)
5144        || !ctx
5145            .analyzer
5146            .type_alias_provider()
5147            .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
5148    {
5149        return None;
5150    }
5151    let indexed_scope = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node);
5152    let owner_scope_matches = member_alias_owner_matches_reference(node, ctx);
5153    if !owner_scope_matches
5154        && !indexed_scope.is_some_and(|scope| {
5155            indexed_scope_matches_target_name(
5156                &scope,
5157                &[ctx.spec.target.identifier().to_string()],
5158                false,
5159                &ctx.spec.target,
5160            )
5161        })
5162    {
5163        return None;
5164    }
5165    // The indexed symbol table intentionally retains declarations from every
5166    // preprocessor branch and from later source positions.  The recovered
5167    // class-owner scope proves the spelling, but it does not prove that this
5168    // alias was active and introduced before the reference.  Apply the same
5169    // structured guard/source-order check used by the ordinary resolver before
5170    // turning the target-guided recovery into a proven hit.
5171    if !(ctx.visibility.external_type_candidate_visible_in_context(
5172        &ctx.analyzer,
5173        ctx.file,
5174        &ctx.spec.target,
5175        node,
5176    ) || owner_scope_matches && member_alias_complete_class_context(node, ctx))
5177    {
5178        return None;
5179    }
5180    let target_visible = ctx
5181        .visibility
5182        .visible_identifier_candidates(ctx.file, ctx.spec.target.identifier())
5183        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target));
5184    target_visible.then_some(node)
5185}
5186
5187/// Recover a class/enum template argument only when the parser's ordinary
5188/// lexical lookup failed but the indexed scope and visible declaration still
5189/// prove the exact target. This intentionally excludes aliases: an alias
5190/// argument needs its own template-argument selection path, while a direct
5191/// class/enum argument can be identified by its canonical scope and symbol.
5192fn target_guided_missing_template_argument_type_leaf<'tree>(
5193    node: Node<'tree>,
5194    ctx: &ScanCtx<'_>,
5195) -> Option<Node<'tree>> {
5196    let target = &ctx.spec.target;
5197    let name = node_text(node, ctx.source);
5198    if !target.is_class()
5199        || !is_cpp_template_argument_type_leaf(node)
5200        || is_declaration_name(node)
5201        || name != target.identifier()
5202        || ctx.local_shadows.is_shadowed(name)
5203        || local_type_name_shadows(node, ctx)
5204        || !ctx.visibility.is_physically_visible(ctx.file, target)
5205        || ctx
5206            .analyzer
5207            .type_alias_provider()
5208            .is_some_and(|provider| provider.is_type_alias(target))
5209    {
5210        return None;
5211    }
5212
5213    let indexed_scope = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)?;
5214    let target_components = canonical_cpp_scope_components(target);
5215    if target_components.last().map(String::as_str) != Some(name)
5216        || !lexical_component_tiers(&[name.to_string()], false, &indexed_scope)
5217            .any(|components| components == target_components)
5218    {
5219        return None;
5220    }
5221
5222    // The direct visible class candidate supplies the declaration identity;
5223    // the scope check above supplies its canonical owner path. Do not let an
5224    // alias or a same-scoped competing class enter this recovery path.
5225    let candidates = visible_type_identifier_candidates(ctx, name);
5226    if candidates.is_empty()
5227        || candidates.iter().any(|candidate| {
5228            !candidate.is_class()
5229                || ctx
5230                    .analyzer
5231                    .type_alias_provider()
5232                    .is_some_and(|provider| provider.is_type_alias(candidate))
5233                || (!same_visible_symbol(candidate, target)
5234                    && lexical_component_tiers(&[name.to_string()], false, &indexed_scope)
5235                        .any(|components| components == canonical_cpp_scope_components(candidate)))
5236        })
5237        || !candidates
5238            .iter()
5239            .any(|candidate| same_visible_symbol(candidate, target))
5240    {
5241        return None;
5242    }
5243
5244    // Physical visibility covers the file/import projection; this second
5245    // guard preserves declaration ordering and preprocessor branch identity.
5246    ctx.visibility
5247        .external_type_candidate_visible_in_context(&ctx.analyzer, ctx.file, target, node)
5248        .then_some(node)
5249}
5250
5251/// Recover the class owner of an out-of-line member whose trailing attribute
5252/// macro was parsed as a separate function definition around the real body.
5253fn split_macro_attribute_out_of_line_owner(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
5254    let mut function = node;
5255    while function.kind() != "function_definition" {
5256        function = ctx.ancestry.parent(function)?;
5257    }
5258    let macro_name = function_definition_name_node(function)?;
5259    if !cpp_export_macro_token(&normalize_cpp_whitespace(node_text(macro_name, ctx.source))) {
5260        return None;
5261    }
5262
5263    // An unknown trailing attribute macro can split one real definition into
5264    // a missing-semicolon declaration for `Owner::method()` and an adjacent
5265    // macro-named function definition that owns the body. Recover only that
5266    // exact CST sequence; a complete declaration or a non-macro function is
5267    // an ordinary independent construct.
5268    let declaration = function.prev_named_sibling()?;
5269    if declaration.kind() != "declaration"
5270        || !declaration.has_error()
5271        || function.start_position().row > declaration.end_position().row + 1
5272    {
5273        return None;
5274    }
5275    let mut missing_semicolon = false;
5276    let mut real_semicolon = false;
5277    for child in children_iter(declaration) {
5278        if child.kind() == ";" {
5279            missing_semicolon |= child.is_missing();
5280            real_semicolon |= !child.is_missing();
5281        }
5282    }
5283    if !missing_semicolon || real_semicolon {
5284        return None;
5285    }
5286
5287    let initializer = declaration.child_by_field_name("declarator")?;
5288    if initializer.kind() != "init_declarator"
5289        || initializer
5290            .child_by_field_name("value")
5291            .is_none_or(|value| value.kind() != "argument_list")
5292    {
5293        return None;
5294    }
5295    let qualified_name = initializer
5296        .child_by_field_name("declarator")
5297        .and_then(declarator_name_node)?;
5298    let qualified = qualified_owner_components(qualified_name, ctx.source)?;
5299    let lexical_scope = enclosing_namespace_components(function, ctx.source);
5300    match ctx.visibility.resolve_type_components_lexically(
5301        &ctx.analyzer,
5302        ctx.file,
5303        &qualified.names,
5304        qualified.global,
5305        &lexical_scope,
5306    ) {
5307        LexicalTypeResolution::Resolved { unit, .. } if unit.is_class() => Some(unit),
5308        LexicalTypeResolution::Resolved { .. }
5309        | LexicalTypeResolution::Ambiguous
5310        | LexicalTypeResolution::Missing => None,
5311    }
5312}
5313
5314/// A class member alias is visible throughout its complete class scope, even
5315/// when its declaration byte follows a recovered out-of-line member's
5316/// trailing return type. Match the indexed owner path structurally before
5317/// allowing the guard-only visibility check above to waive source ordering.
5318fn member_alias_owner_matches_reference(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
5319    member_alias_owner_matches_reference_for(&ctx.spec.target, node, ctx)
5320}
5321
5322fn member_alias_owner_matches_reference_for(
5323    target: &CodeUnit,
5324    node: Node<'_>,
5325    ctx: &ScanCtx<'_>,
5326) -> bool {
5327    let Some(owner) = ctx.analyzer.parent_of(target) else {
5328        return false;
5329    };
5330    if !owner.is_class() {
5331        return false;
5332    }
5333    let reference_owner = ctx
5334        .class_ranges
5335        .and_then(|class_ranges| class_ranges.enclosing_unit(node.start_byte()).cloned())
5336        .or_else(|| structured_enclosing_owner(node, ctx));
5337    if reference_owner.as_ref().is_some_and(|reference_owner| {
5338        ctx.visibility
5339            .same_template_owner_identity(&owner, reference_owner)
5340    }) {
5341        return true;
5342    }
5343    if split_macro_attribute_out_of_line_owner(node, ctx).is_some_and(|reference_owner| {
5344        ctx.visibility
5345            .same_template_owner_identity(&owner, &reference_owner)
5346    }) {
5347        return true;
5348    }
5349    if reference_owner.is_some_and(|reference_owner| {
5350        matches!(
5351            resolve_declaring_member_owner(
5352                &ctx.analyzer,
5353                ctx.visibility,
5354                ctx.file,
5355                &reference_owner,
5356                target.identifier(),
5357            ),
5358            EnclosingMemberOwnerResolution::Owner(declaring_owner)
5359                if ctx
5360                    .visibility
5361                    .same_template_owner_identity(&owner, &declaring_owner)
5362        )
5363    }) {
5364        return true;
5365    }
5366    let range = Range {
5367        start_byte: node.start_byte(),
5368        end_byte: node.end_byte(),
5369        start_line: node.start_position().row + 1,
5370        end_line: node.end_position().row + 1,
5371    };
5372    let mut indexed_enclosing = ctx.analyzer.enclosing_code_unit(ctx.file, &range);
5373    while let Some(candidate) = indexed_enclosing {
5374        if candidate.is_class()
5375            && ctx
5376                .visibility
5377                .same_template_owner_identity(&owner, &candidate)
5378        {
5379            return true;
5380        }
5381        indexed_enclosing = ctx.analyzer.parent_of(&candidate);
5382    }
5383    if let Some(reference_body) = malformed_recovered_class_body(node) {
5384        let mut root = node;
5385        while let Some(parent) = ctx.ancestry.parent(root) {
5386            root = parent;
5387        }
5388        if ctx.analyzer.ranges(target).iter().any(|range| {
5389            root.descendant_for_byte_range(range.start_byte, range.end_byte)
5390                .and_then(malformed_recovered_class_body)
5391                .is_some_and(|declaration_body| same_node(declaration_body, reference_body))
5392        }) {
5393            return true;
5394        }
5395    }
5396    if structured_enclosing_owner(node, ctx)
5397        .is_some_and(|reference_owner| same_logical_symbol(&owner, &reference_owner))
5398    {
5399        return true;
5400    }
5401    let owner_components = canonical_cpp_scope_components(&owner);
5402    if ctx
5403        .recovered_sentinel_scope(node)
5404        .is_some_and(|scope| scope == owner_components)
5405    {
5406        return true;
5407    }
5408    if matches!(
5409        cached_enclosing_lexical_scope_components_with_unresolved_owner(
5410            node,
5411            &ctx.analyzer,
5412            ctx.visibility,
5413            ctx.file,
5414            ctx.source,
5415            false,
5416            false,
5417            Some(&ctx.lexical_scope_cache),
5418        ),
5419        LexicalScopeResolution::Resolved(reference_scope)
5420            if reference_scope == owner_components
5421    ) {
5422        return true;
5423    }
5424    let Some(reference_scope) = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)
5425    else {
5426        return false;
5427    };
5428    !owner_components.is_empty() && reference_scope == owner_components
5429}
5430
5431fn malformed_recovered_class_body(mut node: Node<'_>) -> Option<Node<'_>> {
5432    loop {
5433        if node.kind() == "compound_statement"
5434            && node
5435                .parent()
5436                .is_some_and(|parent| parent.kind() == "declaration_list")
5437            && node.prev_named_sibling().is_some_and(|header| {
5438                header.kind() == "ERROR"
5439                    && header.end_byte() <= node.start_byte()
5440                    && error_contains_class_header(header)
5441            })
5442        {
5443            return Some(node);
5444        }
5445        node = node.parent()?;
5446    }
5447}
5448
5449/// Whether a shallow parser error contains a recognizable class header.
5450pub fn error_contains_class_header(node: Node<'_>) -> bool {
5451    let mut pending = vec![(node, 0usize)];
5452    while let Some((current, depth)) = pending.pop() {
5453        if matches!(current.kind(), "class" | "struct" | "union") {
5454            let mut sibling = current.next_sibling();
5455            let mut saw_name = false;
5456            while let Some(candidate) = sibling {
5457                match candidate.kind() {
5458                    "comment" => {}
5459                    "{" | "base_class_clause" | ":" => return saw_name,
5460                    "identifier" | "type_identifier" if !saw_name => saw_name = true,
5461                    _ if !candidate.is_named() => {}
5462                    _ => break,
5463                }
5464                sibling = candidate.next_sibling();
5465            }
5466        }
5467        if depth >= 1 {
5468            continue;
5469        }
5470        let mut cursor = current.walk();
5471        pending.extend(
5472            current
5473                .children(&mut cursor)
5474                .filter(|child| child.kind() != "compound_statement")
5475                .map(|child| (child, depth + 1)),
5476        );
5477    }
5478    false
5479}
5480
5481fn member_alias_complete_class_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
5482    has_ancestor_kind(node, "compound_statement")
5483        && ctx
5484            .visibility
5485            .external_type_candidate_guard_compatible_in_context(
5486                &ctx.analyzer,
5487                ctx.file,
5488                &ctx.spec.target,
5489                node,
5490            )
5491}
5492
5493fn type_alias_owner_matches_structured_reference(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
5494    ctx.analyzer
5495        .type_alias_provider()
5496        .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
5497        && member_alias_owner_matches_reference(node, ctx)
5498}
5499
5500/// A nested class can use aliases declared by any enclosing class. Preserve
5501/// that structured owner chain for malformed macro-return nodes, whose phantom
5502/// field spelling otherwise makes ordinary lexical lookup ambiguous.
5503fn type_alias_owner_encloses_structured_reference(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
5504    if !ctx
5505        .analyzer
5506        .type_alias_provider()
5507        .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
5508    {
5509        return false;
5510    }
5511    let Some(target_owner) = ctx.analyzer.parent_of(&ctx.spec.target) else {
5512        return false;
5513    };
5514    let mut reference_owner = structured_enclosing_owner(node, ctx);
5515    while let Some(owner) = reference_owner {
5516        if same_logical_symbol(&target_owner, &owner) {
5517            return true;
5518        }
5519        reference_owner = ctx.analyzer.parent_of(&owner);
5520    }
5521    false
5522}
5523
5524/// An enclosing class alias is only usable when no nearer class declares the
5525/// same type name. The recovered macro-return path does not have a complete
5526/// lexical declaration node, so ordinary lookup cannot apply this shadowing
5527/// rule before the enclosing alias fast path runs.
5528fn nearer_type_name_shadows_structured_reference(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
5529    let Some(target_owner) = ctx.analyzer.parent_of(&ctx.spec.target) else {
5530        return false;
5531    };
5532    let Some(alias_provider) = ctx.analyzer.type_alias_provider() else {
5533        return false;
5534    };
5535    let Some(reference_owner) = structured_enclosing_owner(node, ctx) else {
5536        return false;
5537    };
5538    let candidates = ctx
5539        .visibility
5540        .visible_identifier_candidates(ctx.file, ctx.spec.target.identifier())
5541        .filter(|candidate| {
5542            candidate.is_class()
5543                && alias_provider.is_type_alias(candidate)
5544                && !same_visible_symbol(candidate, &ctx.spec.target)
5545        })
5546        .cloned()
5547        .collect::<Vec<_>>();
5548
5549    let mut owner = Some(reference_owner);
5550    while let Some(owner_unit) = owner {
5551        if same_logical_symbol(&target_owner, &owner_unit) {
5552            return false;
5553        }
5554        if candidates.iter().any(|candidate| {
5555            ctx.analyzer
5556                .parent_of(candidate)
5557                .is_some_and(|candidate_owner| {
5558                    candidate_owner.is_class() && same_logical_symbol(&candidate_owner, &owner_unit)
5559                })
5560                && ctx
5561                    .visibility
5562                    .external_type_candidate_guard_compatible_in_context(
5563                        &ctx.analyzer,
5564                        ctx.file,
5565                        candidate,
5566                        node,
5567                    )
5568        }) {
5569            return true;
5570        }
5571        owner = ctx.analyzer.parent_of(&owner_unit);
5572    }
5573    false
5574}
5575
5576fn local_type_name_shadows(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
5577    if cpp_active_template_type_parameter(
5578        node,
5579        ctx.spec.target.identifier(),
5580        ctx.source,
5581        &ctx.ancestry,
5582    ) {
5583        return true;
5584    }
5585    let Some(callable) = nearest_callable_scope(node) else {
5586        return false;
5587    };
5588    let mut root_callable = callable;
5589    let mut ancestor = ctx.ancestry.parent(callable);
5590    while let Some(current) = ancestor {
5591        if matches!(current.kind(), "function_definition" | "lambda_expression") {
5592            root_callable = current;
5593        }
5594        ancestor = ctx.ancestry.parent(current);
5595    }
5596
5597    let mut stack = vec![root_callable];
5598    while let Some(current) = stack.pop() {
5599        if current.start_byte() >= node.start_byte() {
5600            continue;
5601        }
5602        if let Some(name) = local_type_name_declaration_node(current)
5603            && node_text(name, ctx.source) == ctx.spec.target.identifier()
5604            && nearest_callable_scope(current).is_some_and(|owner| {
5605                !is_malformed_wrapper_function_definition(owner)
5606                    && owner.start_byte() <= callable.start_byte()
5607                    && callable.end_byte() <= owner.end_byte()
5608            })
5609            && local_alias_scope_contains_node(current, node)
5610        {
5611            return true;
5612        }
5613        let mut cursor = current.walk();
5614        stack.extend(current.named_children(&mut cursor));
5615    }
5616    false
5617}
5618
5619fn local_type_name_declaration_node(node: Node<'_>) -> Option<Node<'_>> {
5620    local_type_alias_name_node(node).or_else(|| match node.kind() {
5621        "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier" => node
5622            .child_by_field_name("name")
5623            .filter(|name| is_declaration_name(*name)),
5624        _ => None,
5625    })
5626}
5627
5628fn nearest_callable_scope(mut node: Node<'_>) -> Option<Node<'_>> {
5629    loop {
5630        if matches!(node.kind(), "function_definition" | "lambda_expression") {
5631            return Some(node);
5632        }
5633        node = node.parent()?;
5634    }
5635}
5636
5637fn local_type_alias_name_node(node: Node<'_>) -> Option<Node<'_>> {
5638    match node.kind() {
5639        "alias_declaration" => node.child_by_field_name("name"),
5640        "type_definition" => node
5641            .child_by_field_name("declarator")
5642            .and_then(declarator_name_node),
5643        _ => None,
5644    }
5645}
5646
5647fn local_alias_scope_contains_node(alias: Node<'_>, node: Node<'_>) -> bool {
5648    let mut current = alias.parent();
5649    while let Some(parent) = current {
5650        if matches!(
5651            parent.kind(),
5652            "class_specifier" | "struct_specifier" | "union_specifier"
5653        ) {
5654            return false;
5655        }
5656        if parent.kind() == "compound_statement" {
5657            return parent.start_byte() <= node.start_byte()
5658                && node.end_byte() <= parent.end_byte();
5659        }
5660        if matches!(parent.kind(), "function_definition" | "lambda_expression") {
5661            let Some(body) = parent.child_by_field_name("body") else {
5662                return false;
5663            };
5664            return node_is_within(body, alias) && node_is_within(body, node);
5665        }
5666        current = parent.parent();
5667    }
5668    false
5669}
5670
5671fn target_guided_missing_declaration_type_leaf<'tree>(
5672    node: Node<'tree>,
5673    ctx: &ScanCtx<'_>,
5674) -> Option<Node<'tree>> {
5675    if is_declaration_name(node) {
5676        return None;
5677    }
5678    let component_nodes = cpp_name_component_nodes(node)?;
5679    let name_node = component_nodes.last().copied()?;
5680    let name = node_text(name_node, ctx.source);
5681    if name != ctx.spec.target.identifier() {
5682        return None;
5683    }
5684    let inside_target_declaration = ctx
5685        .target_declaration_ranges
5686        .iter()
5687        .any(|range| range.start_byte <= node.start_byte() && node.end_byte() <= range.end_byte);
5688    if !inside_target_declaration
5689        && !ctx.visibility.external_type_candidate_visible_in_context(
5690            &ctx.analyzer,
5691            ctx.file,
5692            &ctx.spec.target,
5693            node,
5694        )
5695    {
5696        return None;
5697    }
5698    let components = component_nodes
5699        .iter()
5700        .map(|component| node_text(*component, ctx.source).to_string())
5701        .collect::<Vec<_>>();
5702    let local_alias_shadow = local_type_name_shadows(node, ctx);
5703    let structured_alias_owner = type_alias_owner_matches_structured_reference(node, ctx);
5704    let indexed_alias_owner = ctx
5705        .analyzer
5706        .type_alias_provider()
5707        .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target))
5708        && member_alias_owner_matches_reference(node, ctx);
5709    let target_alias_self_reference = inside_target_declaration
5710        && ctx
5711            .analyzer
5712            .type_alias_provider()
5713            .is_some_and(|provider| provider.is_type_alias(&ctx.spec.target));
5714    let member_alias_visible = ctx.visibility.external_type_candidate_visible_in_context(
5715        &ctx.analyzer,
5716        ctx.file,
5717        &ctx.spec.target,
5718        node,
5719    ) || member_alias_complete_class_context(node, ctx);
5720    if !target_alias_self_reference
5721        && !local_alias_shadow
5722        && member_alias_visible
5723        && (structured_alias_owner || indexed_alias_owner)
5724    {
5725        return Some(node);
5726    }
5727    let declaration = nearest_declaration_type_context(node)?;
5728    let candidates = visible_type_identifier_candidates(ctx, name);
5729    let unique_visible_target = !candidates.is_empty()
5730        && candidates
5731            .iter()
5732            .all(|candidate| same_visible_symbol(candidate, &ctx.spec.target));
5733    let indexed_scope = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)?;
5734    let exact_scope_match = indexed_scope_matches_target_name(
5735        &indexed_scope,
5736        &components,
5737        is_globally_qualified_cpp_name(node),
5738        &ctx.spec.target,
5739    );
5740    if matches!(declaration.kind(), "field_declaration" | "declaration") {
5741        let parser_lost_declaration_scope =
5742            target_guided_scope_lost_namespace(&indexed_scope, &ctx.spec.target)
5743                && unique_visible_target;
5744        return (exact_scope_match || parser_lost_declaration_scope).then_some(node);
5745    }
5746    let lost_namespace_parameter_context =
5747        matches!(
5748            declaration.kind(),
5749            "parameter_declaration" | "optional_parameter_declaration"
5750        ) && target_guided_scope_lost_namespace(&indexed_scope, &ctx.spec.target);
5751    if exact_scope_match || (lost_namespace_parameter_context && unique_visible_target) {
5752        return Some(node);
5753    }
5754    None
5755}
5756
5757fn target_guided_missing_alias_rhs_type_leaf<'tree>(
5758    node: Node<'tree>,
5759    ctx: &ScanCtx<'_>,
5760) -> Option<Node<'tree>> {
5761    let mut stack = vec![node];
5762    while let Some(candidate) = stack.pop() {
5763        if candidate.kind() == "type_identifier"
5764            && !is_declaration_name(candidate)
5765            && matches!(
5766                ctx.ancestry.parent(candidate).map(|parent| parent.kind()),
5767                Some("template_type")
5768            )
5769        {
5770            let mut current = ctx.ancestry.parent(candidate);
5771            let mut saw_qualified = false;
5772            let mut saw_dependent = false;
5773            let mut saw_type_descriptor = false;
5774            let mut saw_alias_declaration = false;
5775            while let Some(ancestor) = current {
5776                match ancestor.kind() {
5777                    "qualified_identifier" | "scoped_type_identifier" => saw_qualified = true,
5778                    "dependent_type" => saw_dependent = true,
5779                    "type_descriptor" => saw_type_descriptor = true,
5780                    "alias_declaration" => {
5781                        saw_alias_declaration = true;
5782                        break;
5783                    }
5784                    "template_type"
5785                    | "template_argument_list"
5786                    | "typename"
5787                    | "template_declaration" => {}
5788                    _ => {}
5789                }
5790                current = ctx.ancestry.parent(ancestor);
5791            }
5792            let name = node_text(candidate, ctx.source);
5793            let visible_candidates = visible_type_identifier_candidates(ctx, name);
5794            let canonical_alias_target = visible_candidates
5795                .iter()
5796                .filter_map(|alias| ctx.visibility.alias_target(alias))
5797                .any(|target| same_visible_symbol(&target, &ctx.spec.target));
5798            let alias_resolves =
5799                ctx.visibility
5800                    .parser_alias_resolves_to_type(ctx.file, name, &ctx.spec.target)
5801                    || canonical_alias_target;
5802            if saw_qualified
5803                && saw_dependent
5804                && saw_type_descriptor
5805                && saw_alias_declaration
5806                && alias_resolves
5807                && ctx.visibility.external_type_candidate_visible_in_context(
5808                    &ctx.analyzer,
5809                    ctx.file,
5810                    &ctx.spec.target,
5811                    candidate,
5812                )
5813            {
5814                return Some(candidate);
5815            }
5816        }
5817        push_named_children_reversed(candidate, &mut stack);
5818    }
5819    None
5820}
5821
5822fn nearest_declaration_type_context(node: Node<'_>) -> Option<Node<'_>> {
5823    let mut current = Some(node);
5824    while let Some(ancestor) = current {
5825        if matches!(
5826            ancestor.kind(),
5827            "field_declaration"
5828                | "parameter_declaration"
5829                | "optional_parameter_declaration"
5830                | "declaration"
5831                | "type_descriptor"
5832        ) {
5833            let contains_type = crate::declarations::cpp_type_field_contains_node(ancestor, node);
5834            if contains_type
5835                && !(ancestor.kind() == "type_descriptor"
5836                    && is_cpp_template_argument_type_leaf(node))
5837            {
5838                return Some(ancestor);
5839            }
5840            if ancestor.kind() == "type_descriptor"
5841                && ancestor.parent().is_some_and(|parent| {
5842                    matches!(
5843                        parent.kind(),
5844                        "cast_expression"
5845                            | "new_expression"
5846                            | "sizeof_expression"
5847                            | "alignof_expression"
5848                            | "typeid_expression"
5849                    )
5850                })
5851            {
5852                return Some(ancestor);
5853            }
5854        }
5855        if matches!(
5856            ancestor.kind(),
5857            "compound_statement"
5858                | "translation_unit"
5859                | "namespace_definition"
5860                | "alias_declaration"
5861                | "type_definition"
5862                | "base_class_clause"
5863        ) {
5864            return None;
5865        }
5866        current = ancestor.parent();
5867    }
5868    None
5869}
5870
5871fn visible_type_identifier_candidates(ctx: &ScanCtx<'_>, name: &str) -> Vec<CodeUnit> {
5872    let mut candidates = Vec::new();
5873    for candidate in ctx
5874        .visibility
5875        .visible_identifier_candidates(ctx.file, name)
5876        .filter(|candidate| {
5877            candidate.is_class()
5878                || ctx
5879                    .analyzer
5880                    .type_alias_provider()
5881                    .is_some_and(|provider| provider.is_type_alias(candidate))
5882        })
5883    {
5884        if !candidates
5885            .iter()
5886            .any(|existing| same_logical_symbol(existing, candidate))
5887        {
5888            candidates.push(candidate.clone());
5889        }
5890    }
5891    candidates
5892}
5893
5894/// Recover a direct type-alias argument of `static_cast` when parser recovery
5895/// misclassifies a namespace alias as a local declaration. The indexed scope
5896/// and exact alias identity are required so a same-spelled alias in another
5897/// namespace remains excluded.
5898fn target_guided_static_cast_alias_type_descriptor<'tree>(
5899    node: Node<'tree>,
5900    ctx: &ScanCtx<'_>,
5901) -> Option<Node<'tree>> {
5902    if node.kind() != "type_descriptor" {
5903        return None;
5904    }
5905    let argument_list = ctx.ancestry.parent(node).filter(|parent| {
5906        parent.kind() == "template_argument_list"
5907            && parent.named_child_count() == 1
5908            && parent.named_child(0) == Some(node)
5909    })?;
5910    let template = ctx.ancestry.parent(argument_list).filter(|parent| {
5911        parent.kind() == "template_function"
5912            && parent.child_by_field_name("arguments") == Some(argument_list)
5913    })?;
5914    let name = template.child_by_field_name("name")?;
5915    if name.kind() != "identifier" || node_text(name, ctx.source) != "static_cast" {
5916        return None;
5917    }
5918    let target = &ctx.spec.target;
5919    if node_text(node, ctx.source) != target.identifier()
5920        || !ctx
5921            .analyzer
5922            .type_alias_provider()
5923            .is_some_and(|provider| provider.is_type_alias(target))
5924        || !ctx.visibility.is_physically_visible(ctx.file, target)
5925        || !ctx.visibility.external_type_candidate_visible_in_context(
5926            &ctx.analyzer,
5927            ctx.file,
5928            target,
5929            node,
5930        )
5931    {
5932        return None;
5933    }
5934
5935    let indexed_scope = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)?;
5936    let target_scope = canonical_cpp_scope_components(target);
5937    let name_components = [target.identifier().to_string()];
5938    if !lexical_component_tiers(&name_components, false, &indexed_scope)
5939        .any(|components| components == target_scope)
5940    {
5941        return None;
5942    }
5943
5944    let candidates = visible_type_identifier_candidates(ctx, target.identifier());
5945    if !candidates
5946        .iter()
5947        .any(|candidate| same_visible_symbol(candidate, target))
5948    {
5949        return None;
5950    }
5951    if candidates.iter().any(|candidate| {
5952        !same_visible_symbol(candidate, target)
5953            && lexical_component_tiers(&name_components, false, &indexed_scope)
5954                .any(|components| components == canonical_cpp_scope_components(candidate))
5955    }) {
5956        return None;
5957    }
5958    Some(node)
5959}
5960
5961fn indexed_scope_matches_target_name(
5962    indexed_scope: &[String],
5963    components: &[String],
5964    global: bool,
5965    target: &CodeUnit,
5966) -> bool {
5967    let target_name = cpp_name_for(target);
5968    lexical_component_tiers(components, global, indexed_scope)
5969        .any(|qualified| qualified.join("::") == target_name)
5970}
5971
5972fn target_guided_scope_lost_namespace(indexed_scope: &[String], target: &CodeUnit) -> bool {
5973    // A global scope or one surviving name alone cannot distinguish a lost
5974    // namespace from a real global/unrelated reference. Require an enclosing
5975    // declaration component as well as a namespace component matching the
5976    // target's qualified scope.
5977    if target.package_name().is_empty() || indexed_scope.len() <= 1 {
5978        return false;
5979    }
5980    let mut target_scope = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
5981        brokk_bifrost_core::analyzer::Language::Cpp,
5982        &cpp_name_for(target),
5983    );
5984    target_scope.pop();
5985    (1..indexed_scope.len())
5986        .rev()
5987        .any(|prefix_len| target_scope.ends_with(&indexed_scope[..prefix_len]))
5988}
5989
5990fn indexed_enclosing_lexical_scope(
5991    analyzer: &CppGraphSource<'_>,
5992    file: &ProjectFile,
5993    node: Node<'_>,
5994) -> Option<Vec<String>> {
5995    let range = Range {
5996        start_byte: node.start_byte(),
5997        end_byte: node.end_byte(),
5998        start_line: node.start_position().row,
5999        end_line: node.end_position().row,
6000    };
6001    let enclosing = analyzer.enclosing_code_unit(file, &range)?;
6002    let mut components = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
6003        brokk_bifrost_core::analyzer::Language::Cpp,
6004        &cpp_name_for(&enclosing),
6005    );
6006    if !enclosing.is_class() && !enclosing.is_module() {
6007        components.pop();
6008    }
6009    Some(components)
6010}
6011
6012fn static_qualifier_name_scope<'tree>(node: Node<'tree>, ctx: &ScanCtx<'_>) -> Option<Node<'tree>> {
6013    if node.kind() != "qualified_identifier" {
6014        return None;
6015    }
6016    let mut stack = vec![node];
6017    while let Some(current) = stack.pop() {
6018        if current.kind() != "qualified_identifier" {
6019            continue;
6020        }
6021        if let Some(scope) = current.child_by_field_name("scope") {
6022            let text = qualified_scope_text(scope, ctx.source);
6023            if name_mentions(&text, &ctx.spec.member_name) {
6024                return Some(scope);
6025            }
6026        }
6027        let mut cursor = current.walk();
6028        for child in current.named_children(&mut cursor) {
6029            if child.kind() == "qualified_identifier" {
6030                stack.push(child);
6031            }
6032        }
6033    }
6034    None
6035}
6036
6037fn qualified_scope_text(scope: Node<'_>, source: &str) -> String {
6038    let mut parts = vec![node_text(scope, source).to_string()];
6039    let mut current = scope.parent();
6040    while let Some(qualified) = current {
6041        let Some(parent) = qualified.parent() else {
6042            break;
6043        };
6044        if parent.kind() != "qualified_identifier"
6045            || parent.child_by_field_name("name") != Some(qualified)
6046        {
6047            break;
6048        }
6049        if let Some(outer_scope) = parent.child_by_field_name("scope") {
6050            parts.push(node_text(outer_scope, source).to_string());
6051        }
6052        current = Some(parent);
6053    }
6054    parts.reverse();
6055    parts.join("::")
6056}
6057
6058fn maybe_record_constructor_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6059    if node.kind() == "using_declaration" {
6060        maybe_record_using_callable_hit(node, ctx);
6061        return;
6062    }
6063    if has_ancestor_kind(node, "using_declaration") {
6064        return;
6065    }
6066    if node.kind() == "function_definition" {
6067        return;
6068    }
6069    if !matches!(
6070        node.kind(),
6071        "call_expression"
6072            | "new_expression"
6073            | "compound_literal_expression"
6074            | "declaration"
6075            | "field_initializer"
6076    ) {
6077        return;
6078    }
6079    let Some(owner) = ctx.spec.owner.as_ref() else {
6080        return;
6081    };
6082    if node.kind() == "field_initializer" {
6083        if !field_initializer_constructs_target(node, ctx, owner)
6084            && !unqualified_base_initializer_constructs_target(node, ctx, owner)
6085        {
6086            return;
6087        }
6088        if let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) {
6089            match ctx
6090                .visibility
6091                .call_arity_evidence(ctx.file, node, ctx.source)
6092                .accepts(expected)
6093            {
6094                Some(true) => {}
6095                Some(false) => return,
6096                None => {
6097                    push_unproven_hit(node, ctx);
6098                    return;
6099                }
6100            }
6101        }
6102        match constructor_overload_selection(node, ctx) {
6103            ConstructorOverloadSelection::Target => push_hit(node, ctx),
6104            ConstructorOverloadSelection::Ambiguous => push_unproven_hit(node, ctx),
6105            ConstructorOverloadSelection::OtherOverload => {}
6106        }
6107        return;
6108    }
6109    if node.kind() == "declaration" {
6110        if declaration_is_object_construction_candidate(node, ctx)
6111            && declaration_mentions_type(node, ctx, owner)
6112            && ctx
6113                .spec
6114                .callable_arity_at(node.start_byte())
6115                .is_none_or(|expected| expected.accepts(declaration_constructor_arity(node, ctx)))
6116        {
6117            match constructor_overload_selection(node, ctx) {
6118                ConstructorOverloadSelection::Target => push_hit(node, ctx),
6119                ConstructorOverloadSelection::Ambiguous => push_unproven_hit(node, ctx),
6120                ConstructorOverloadSelection::OtherOverload => {}
6121            }
6122        }
6123        return;
6124    }
6125    let Some(type_node) = constructor_type_node(node) else {
6126        return;
6127    };
6128    let hit_node = function_terminal_node(type_node);
6129    let text = node_text(type_node, ctx.source);
6130    if !name_mentions(text, &ctx.spec.member_name) {
6131        return;
6132    }
6133    *ctx.raw_match_count += 1;
6134    if let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) {
6135        match ctx
6136            .visibility
6137            .call_arity_evidence(ctx.file, node, ctx.source)
6138            .accepts(expected)
6139        {
6140            Some(true) => {}
6141            Some(false) => return,
6142            None => {
6143                push_unproven_hit(hit_node, ctx);
6144                return;
6145            }
6146        }
6147    }
6148    match constructor_overload_selection(node, ctx) {
6149        ConstructorOverloadSelection::Target => {}
6150        ConstructorOverloadSelection::Ambiguous => {
6151            push_unproven_hit(hit_node, ctx);
6152            return;
6153        }
6154        ConstructorOverloadSelection::OtherOverload => return,
6155    }
6156    let structured_resolution = resolve_type_node_lexically_for_target(
6157        type_node,
6158        &ctx.analyzer,
6159        ctx.visibility,
6160        &ctx.ordinary_type_imports,
6161        ctx.file,
6162        ctx.source,
6163        owner,
6164        Some(&ctx.lexical_scope_cache),
6165        ctx.recovered_sentinel_scope(type_node).as_deref(),
6166    );
6167    let structurally_resolves = matches!(
6168        &structured_resolution,
6169        LexicalTypeResolution::Resolved {
6170            unit, candidates, ..
6171        } if same_visible_symbol(unit, owner)
6172            || candidates
6173                .iter()
6174                .any(|candidate| same_visible_symbol(candidate, owner))
6175    );
6176    if structurally_resolves
6177        || matches!(structured_resolution, LexicalTypeResolution::Missing)
6178            && ctx
6179                .visibility
6180                .resolves_to_type(&ctx.analyzer, ctx.file, text, owner)
6181    {
6182        push_hit(hit_node, ctx);
6183    } else {
6184        push_unproven_hit(hit_node, ctx);
6185    }
6186}
6187
6188/// What the overload filter says about a construction site relative to the
6189/// constructor being scanned.
6190enum ConstructorOverloadSelection {
6191    /// The arguments leave the scan target as the only viable constructor, or
6192    /// the filter has no evidence to apply here. Either way nothing about the
6193    /// arguments argues against the site, so the rest of the scan decides it.
6194    Target,
6195    /// More than one of the owner's constructors stays viable, so the site
6196    /// cannot be proven to belong to the target.
6197    Ambiguous,
6198    /// The arguments select a sibling constructor and not the target.
6199    OtherOverload,
6200}
6201
6202/// Which of the owner's constructors the arguments at a construction site
6203/// select, for every shape `maybe_record_constructor_hit` accepts: `T(args)`,
6204/// `T{args}`, `new T(args)`, the member initializer `: field(args)`, and the
6205/// `T var(args)` declaration.
6206///
6207/// This is the inverse reading of the forward direction's overload choice. The
6208/// candidate set is the owner's arity-compatible constructors, the arguments are
6209/// typed by the same `expression_arg_type` the method and free-function scan
6210/// paths use, and `cpp_filter_candidates_by_args_with_parameter_types` applies
6211/// the same exact-then-conversion ranking (#2894). Selecting a constructor by
6212/// arity alone made a scan of one overload claim every same-arity sibling's call
6213/// (#2908).
6214fn constructor_overload_selection(
6215    node: Node<'_>,
6216    ctx: &ScanCtx<'_>,
6217) -> ConstructorOverloadSelection {
6218    let Some(owner) = ctx.spec.owner.as_ref() else {
6219        return ConstructorOverloadSelection::Target;
6220    };
6221    if ctx.spec.param_types.is_none() {
6222        return ConstructorOverloadSelection::Target;
6223    }
6224    // A `T var(args)` declaration keeps its arguments under the declarator or the
6225    // init declarator's value; every other shape spells an argument list that the
6226    // shared call helpers find, and its argument count needs the macro-aware
6227    // arity evidence.
6228    let (arity, arg_types) = if node.kind() == "declaration" {
6229        match declaration_constructor_initializer(node) {
6230            DeclarationConstructorInitializer::Arguments(arguments) => (
6231                argument_children(arguments).count(),
6232                argument_list_types(arguments, ctx),
6233            ),
6234            DeclarationConstructorInitializer::Expression(value) => {
6235                (1, vec![expression_arg_type(value, ctx)])
6236            }
6237            DeclarationConstructorInitializer::Empty => (0, Vec::new()),
6238        }
6239    } else {
6240        let Some(arity) = ctx
6241            .visibility
6242            .call_arity_evidence(ctx.file, node, ctx.source)
6243            .exact()
6244        else {
6245            return ConstructorOverloadSelection::Target;
6246        };
6247        (arity, call_argument_types(node, ctx))
6248    };
6249    let mut candidates = ctx
6250        .visibility
6251        .visible_members_for_owner_name(ctx.file, owner, &ctx.spec.member_name)
6252        .into_iter()
6253        .filter(|unit| unit.is_function())
6254        .cloned()
6255        .collect::<Vec<_>>();
6256    candidates.retain(|unit| {
6257        cpp_callable_arity(&ctx.analyzer, unit).is_none_or(|known| known.accepts(arity))
6258    });
6259    if !candidates
6260        .iter()
6261        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
6262    {
6263        return ConstructorOverloadSelection::Target;
6264    }
6265    let filtered = cpp_filter_candidates_by_args_with_parameter_types(
6266        candidates,
6267        &arg_types,
6268        &|candidate| cpp_callable_parameter_types(&ctx.analyzer, candidate),
6269        &|candidate| {
6270            ctx.visibility
6271                .callable_is_template_declaration(&ctx.analyzer, candidate)
6272        },
6273        &|name| ctx.visibility.resolve_type(ctx.file, name),
6274        &|left, right| same_visible_symbol(left, right),
6275    );
6276    if !filtered
6277        .iter()
6278        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
6279    {
6280        return ConstructorOverloadSelection::OtherOverload;
6281    }
6282    // A header declaration and its out-of-line body are one constructor even
6283    // when their persisted signature strings spell a parameter differently, so
6284    // `same_logical_callable` decides what counts as a surviving sibling (#2010).
6285    if filtered.iter().all(|candidate| {
6286        ctx.visibility
6287            .same_logical_callable(&ctx.analyzer, candidate, &ctx.spec.target)
6288    }) {
6289        ConstructorOverloadSelection::Target
6290    } else {
6291        ConstructorOverloadSelection::Ambiguous
6292    }
6293}
6294
6295fn unqualified_base_initializer_constructs_target(
6296    node: Node<'_>,
6297    ctx: &ScanCtx<'_>,
6298    target_owner: &CodeUnit,
6299) -> bool {
6300    if first_named_child_of_kind(node, "qualified_identifier").is_some() {
6301        return false;
6302    }
6303    let Some(name) = node
6304        .child_by_field_name("name")
6305        .or_else(|| first_named_child_of_kind(node, "field_identifier"))
6306    else {
6307        return false;
6308    };
6309    if node_text(name, ctx.source) != ctx.spec.member_name {
6310        return false;
6311    }
6312    let Some(enclosing_owner) = structured_enclosing_owner(node, ctx) else {
6313        return false;
6314    };
6315    let inherited = ctx.visibility.inherited_injected_class_owner(
6316        &ctx.analyzer,
6317        ctx.file,
6318        &enclosing_owner,
6319        &ctx.spec.member_name,
6320    );
6321    inherited.is_some_and(|owner| {
6322        receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx)
6323    })
6324}
6325
6326fn maybe_record_free_function_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6327    if node.kind() == "function_definition" {
6328        maybe_record_free_function_definition_hit(node, ctx);
6329        return;
6330    }
6331    if node.kind() == "function_declarator" {
6332        maybe_record_recovered_error_free_function_call(node, ctx);
6333        return;
6334    }
6335    if node.kind() == "identifier" {
6336        maybe_record_free_function_value_reference(node, ctx);
6337        return;
6338    }
6339    if node.kind() != "call_expression" {
6340        return;
6341    }
6342    let Some(function) = node
6343        .child_by_field_name("function")
6344        .or_else(|| node.named_child(0))
6345    else {
6346        return;
6347    };
6348    let text = node_text(function, ctx.source);
6349    if !name_matches_callable(text, &ctx.spec.member_name) {
6350        return;
6351    }
6352    *ctx.raw_match_count += 1;
6353    if let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) {
6354        match ctx
6355            .visibility
6356            .call_arity_evidence(ctx.file, node, ctx.source)
6357            .accepts(expected)
6358        {
6359            Some(true) => {}
6360            Some(false) => return,
6361            None => {
6362                // The argument count is unknown after macro expansion. It still
6363                // cannot select a *different* target when the bare name binds
6364                // to exactly one visible callable, so let the bare-call
6365                // resolution below prove that site; every other shape stays
6366                // unproven (#1811, the scan side of the same over-conservatism
6367                // that made the forward answer discard its lone candidate).
6368                if !bare_name_binds_only_target(node, function, text, ctx) {
6369                    push_unproven_hit(function_terminal_node(function), ctx);
6370                    return;
6371                }
6372            }
6373        }
6374    }
6375    if matches!(function.kind(), "identifier" | "template_function") {
6376        let terminal = function_terminal_node(function);
6377        let name = node_text(terminal, ctx.source);
6378        if ctx.local_shadows.is_shadowed(name) {
6379            return;
6380        }
6381        if let Some(enclosing_owner) = structured_enclosing_owner(function, ctx)
6382            && !matches!(
6383                resolve_declaring_member_owner(
6384                    &ctx.analyzer,
6385                    ctx.visibility,
6386                    ctx.file,
6387                    &enclosing_owner,
6388                    name,
6389                ),
6390                EnclosingMemberOwnerResolution::Missing
6391            )
6392        {
6393            return;
6394        }
6395        match resolve_bare_call_target(
6396            node,
6397            function,
6398            &ctx.analyzer,
6399            ctx.visibility,
6400            &ctx.ordinary_type_imports,
6401            ctx.file,
6402            ctx.source,
6403        ) {
6404            BareCallTargetResolution::FreeFunctions(units)
6405                if units
6406                    .iter()
6407                    .any(|unit| free_function_target_matches(unit, ctx)) =>
6408            {
6409                if free_function_call_may_target(node, text, ctx) {
6410                    let recursive = enclosing_context(terminal, ctx)
6411                        .enclosing
6412                        .as_ref()
6413                        .is_some_and(|enclosing| same_logical_symbol(enclosing, &ctx.spec.target));
6414                    if recursive {
6415                        push_recursive_reference_hit(terminal, ctx);
6416                    } else {
6417                        push_hit(terminal, ctx);
6418                    }
6419                }
6420            }
6421            BareCallTargetResolution::UnprovenFreeFunctions(units)
6422                if units
6423                    .iter()
6424                    .any(|unit| free_function_target_matches(unit, ctx)) =>
6425            {
6426                push_unproven_hit(terminal, ctx);
6427            }
6428            BareCallTargetResolution::FreeFunctions(_)
6429            | BareCallTargetResolution::UnprovenFreeFunctions(_)
6430            | BareCallTargetResolution::Type(_)
6431            | BareCallTargetResolution::CallableShadow => {}
6432            BareCallTargetResolution::Ambiguous | BareCallTargetResolution::Missing => {
6433                push_unproven_hit(terminal, ctx);
6434            }
6435        }
6436        return;
6437    }
6438    if !free_function_call_may_target(node, text, ctx) {
6439        return;
6440    }
6441    if ctx.visibility.contains_named_symbol(
6442        ctx.file,
6443        text,
6444        TargetKind::FreeFunction,
6445        &ctx.spec.target,
6446    ) {
6447        push_hit(function_terminal_node(function), ctx);
6448    } else if ctx.visibility.resolve_known_non_target(
6449        ctx.file,
6450        text,
6451        TargetKind::FreeFunction,
6452        &ctx.spec.target,
6453    ) {
6454        // An explicitly namespace-qualified call to a different namespace (e.g. `other::run()` when
6455        // the target is `ns::run`) is a proven non-match, not an unresolved reference.
6456    } else {
6457        push_unproven_hit(function_terminal_node(function), ctx);
6458    }
6459}
6460
6461fn free_function_target_matches(unit: &CodeUnit, ctx: &ScanCtx<'_>) -> bool {
6462    same_visible_symbol(unit, &ctx.spec.target)
6463        || ctx
6464            .visibility
6465            .same_logical_callable(&ctx.analyzer, unit, &ctx.spec.target)
6466            && cpp_callable_definitions_share_identity_evidence_with_visibility(
6467                &ctx.analyzer,
6468                ctx.visibility,
6469                unit,
6470                &ctx.spec.target,
6471            )
6472}
6473
6474/// Recover a bare call whose adjacent object-like macro arguments made
6475/// tree-sitter place a `function_declarator` directly under an `ERROR` node.
6476///
6477/// For example, `check(mount(A, PREFIX SUFFIX, 0))` loses the inner
6478/// `call_expression`, but retains `mount(...)` as a structured declarator. A
6479/// real block-scope function declaration remains under a `declaration`, so the
6480/// direct `ERROR` parent and compound-statement ancestry keep this recovery
6481/// out of declaration syntax. The malformed parameter list cannot establish
6482/// arity; publish a proven hit only when ordinary visibility leaves one
6483/// callable identity for the bare name.
6484fn maybe_record_recovered_error_free_function_call(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6485    if ctx
6486        .ancestry
6487        .parent(node)
6488        .is_none_or(|parent| parent.kind() != "ERROR")
6489        || !has_ancestor_kind(node, "compound_statement")
6490    {
6491        return;
6492    }
6493    let mut recovered_functions = Vec::new();
6494    if let Some(function) = node
6495        .child_by_field_name("declarator")
6496        .filter(|function| function.kind() == "identifier")
6497    {
6498        recovered_functions.push(function);
6499    }
6500    if let Some(parameters) = node.child_by_field_name("parameters") {
6501        let mut cursor = parameters.walk();
6502        for parameter in parameters
6503            .named_children(&mut cursor)
6504            .filter(|child| child.kind() == "parameter_declaration")
6505        {
6506            if parameter
6507                .child_by_field_name("declarator")
6508                .is_some_and(|declarator| declarator.kind() == "abstract_function_declarator")
6509                && let Some(function) = parameter
6510                    .child_by_field_name("type")
6511                    .filter(|function| function.kind() == "type_identifier")
6512            {
6513                recovered_functions.push(function);
6514            }
6515        }
6516    }
6517
6518    for function in recovered_functions {
6519        let name = node_text(function, ctx.source);
6520        if !name_matches_callable(name, &ctx.spec.member_name)
6521            || ctx.local_shadows.is_shadowed(name)
6522        {
6523            continue;
6524        }
6525        *ctx.raw_match_count += 1;
6526        if bare_name_at_binds_only_target(function.start_byte(), name, ctx) {
6527            push_hit(function, ctx);
6528            continue;
6529        }
6530        let mut candidates =
6531            ctx.visibility
6532                .named_candidates(ctx.file, name, TargetKind::FreeFunction);
6533        candidates.retain(|candidate| {
6534            ctx.visibility.declaration_visible_at(
6535                &ctx.analyzer,
6536                ctx.file,
6537                candidate,
6538                function.start_byte(),
6539            )
6540        });
6541        dedupe_callable_candidates(&mut candidates, &ctx.analyzer, ctx.visibility);
6542        if candidates
6543            .iter()
6544            .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
6545        {
6546            push_unproven_hit(function, ctx);
6547        }
6548    }
6549}
6550
6551/// Whether the bare name at `call` binds to exactly one visible callable, and
6552/// that callable is the scan target.
6553///
6554/// This is the scan-side reading of the #1811 rule: with one name binding there
6555/// is nothing an unknown argument count could select instead, so the site is a
6556/// proven reference rather than an unproven one. Only bare identifiers qualify;
6557/// a member or qualified call reaches its target through a receiver this cannot
6558/// judge.
6559fn bare_name_binds_only_target(
6560    call: Node<'_>,
6561    function: Node<'_>,
6562    text: &str,
6563    ctx: &ScanCtx<'_>,
6564) -> bool {
6565    if !matches!(function.kind(), "identifier" | "template_function") {
6566        return false;
6567    }
6568    bare_name_at_binds_only_target(call.start_byte(), text, ctx)
6569}
6570
6571fn bare_name_at_binds_only_target(reference_byte: usize, text: &str, ctx: &ScanCtx<'_>) -> bool {
6572    let mut candidates = ctx
6573        .visibility
6574        .named_candidates(ctx.file, text, TargetKind::FreeFunction);
6575    candidates.retain(|candidate| {
6576        ctx.visibility
6577            .declaration_visible_at(&ctx.analyzer, ctx.file, candidate, reference_byte)
6578    });
6579    dedupe_callable_candidates(&mut candidates, &ctx.analyzer, ctx.visibility);
6580    matches!(candidates.as_slice(), [only] if same_visible_symbol(only, &ctx.spec.target))
6581}
6582
6583fn free_function_call_may_target(call: Node<'_>, text: &str, ctx: &ScanCtx<'_>) -> bool {
6584    if ctx.spec.param_types.is_none() {
6585        return true;
6586    }
6587    let mut candidates = ctx
6588        .visibility
6589        .named_candidates(ctx.file, text, TargetKind::FreeFunction);
6590    candidates.retain(|candidate| {
6591        ctx.visibility
6592            .declaration_visible_at(&ctx.analyzer, ctx.file, candidate, call.start_byte())
6593    });
6594    callable_candidates_may_match_target(call, candidates, ctx)
6595}
6596
6597fn callable_candidates_may_match_target(
6598    call: Node<'_>,
6599    mut candidates: Vec<CodeUnit>,
6600    ctx: &ScanCtx<'_>,
6601) -> bool {
6602    let Some(arity) = ctx
6603        .visibility
6604        .call_arity_evidence(ctx.file, call, ctx.source)
6605        .exact()
6606    else {
6607        return true;
6608    };
6609    candidates.retain(|unit| {
6610        cpp_callable_arity(&ctx.analyzer, unit).is_none_or(|known| known.accepts(arity))
6611    });
6612    if candidates.is_empty()
6613        || !candidates
6614            .iter()
6615            .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
6616    {
6617        return true;
6618    }
6619    let arg_types = call_argument_types(call, ctx);
6620    let filtered = cpp_filter_candidates_by_args_with_parameter_types(
6621        candidates,
6622        &arg_types,
6623        &|candidate| cpp_callable_parameter_types(&ctx.analyzer, candidate),
6624        &|candidate| {
6625            ctx.visibility
6626                .callable_is_template_declaration(&ctx.analyzer, candidate)
6627        },
6628        &|name| ctx.visibility.resolve_type(ctx.file, name),
6629        &|left, right| same_visible_symbol(left, right),
6630    );
6631    filtered
6632        .iter()
6633        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
6634}
6635
6636/// The types of the arguments an `argument_list` or `initializer_list` supplies,
6637/// in order.
6638///
6639/// A `None` entry is an argument the index cannot type; one of them makes
6640/// `cpp_filter_candidates_by_args` keep every candidate rather than guess.
6641fn argument_list_types(arguments: Node<'_>, ctx: &ScanCtx<'_>) -> Vec<Option<CppArgType>> {
6642    argument_children(arguments)
6643        .map(|arg| expression_arg_type(arg, ctx))
6644        .collect()
6645}
6646
6647fn call_argument_types(call: Node<'_>, ctx: &ScanCtx<'_>) -> Vec<Option<CppArgType>> {
6648    call_arguments_node(call)
6649        .map(|arguments| argument_list_types(arguments, ctx))
6650        .unwrap_or_default()
6651}
6652
6653fn expression_arg_type(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CppArgType> {
6654    match node.kind() {
6655        "number_literal" | "true" | "false" | "char_literal" | "string_literal"
6656        | "unary_expression" => cpp_literal_arg_type(node, ctx.source).map(|mut literal| {
6657            literal.unit = ctx.visibility.resolve_type(ctx.file, &literal.name);
6658            literal
6659        }),
6660        "identifier" => identifier_arg_type(node, node_text(node, ctx.source), ctx),
6661        // `T v(x);` is the vexing parse: the grammar reads it as a function
6662        // declaration whose one parameter is `x` spelled as a type. A parameter
6663        // declaration that is nothing but a type identifier is that reading, and
6664        // the identifier it holds is the constructor argument.
6665        "parameter_declaration" => {
6666            let declared = node.child_by_field_name("type")?;
6667            (node.child_by_field_name("declarator").is_none()
6668                && declared.kind() == "type_identifier")
6669                .then(|| identifier_arg_type(declared, node_text(declared, ctx.source), ctx))
6670                .flatten()
6671        }
6672        // `this->m_params` names the same data member as the bare `m_params`.
6673        "field_expression" => {
6674            let receiver = node
6675                .child_by_field_name("argument")
6676                .or_else(|| node.named_child(0))?;
6677            let field = node.child_by_field_name("field")?;
6678            (receiver.kind() == "this")
6679                .then(|| enclosing_member_field_arg_type(node, node_text(field, ctx.source), ctx))
6680                .flatten()
6681        }
6682        "parenthesized_expression" => node
6683            .child_by_field_name("argument")
6684            .or_else(|| node.named_child(0))
6685            .and_then(|inner| expression_arg_type(inner, ctx)),
6686        // `std::move(t)` and `std::forward<T>(t)` have the type of what they
6687        // forward (#2552).
6688        "call_expression" => {
6689            let forwarded = cpp_forwarding_call_argument(node, ctx.source)?;
6690            expression_arg_type(forwarded, ctx)
6691        }
6692        "pointer_expression" => {
6693            let delta = match node.child_by_field_name("operator")?.kind() {
6694                "&" => 1,
6695                "*" => -1,
6696                _ => return None,
6697            };
6698            let inner = node
6699                .child_by_field_name("argument")
6700                .or_else(|| node.named_child(0))?;
6701            let mut arg_type = expression_arg_type(inner, ctx)?;
6702            arg_type.indirection += delta;
6703            Some(arg_type)
6704        }
6705        _ => None,
6706    }
6707}
6708
6709/// The type of a bare value name used as a call argument: the local or
6710/// parameter binding when one is in scope, otherwise the enclosing class's data
6711/// member of that name.
6712///
6713/// Unqualified lookup reaches a local before a data member, so a local of the
6714/// same name ends the search rather than falling through to the field. This
6715/// mirrors `cpp_identifier_value_type` on the forward side, which is what keeps
6716/// the two directions agreeing about which overload a member-field argument
6717/// selects (#2894).
6718fn identifier_arg_type(node: Node<'_>, name: &str, ctx: &ScanCtx<'_>) -> Option<CppArgType> {
6719    match ctx.bindings.resolve_symbol(name) {
6720        SymbolResolution::Precise(bindings) => {
6721            bindings.iter().find_map(CppScanBinding::as_arg_type)
6722        }
6723        SymbolResolution::Ambiguous => None,
6724        SymbolResolution::Unknown => (!ctx.local_shadows.is_shadowed(name))
6725            .then(|| enclosing_member_field_arg_type(node, name, ctx))
6726            .flatten(),
6727    }
6728}
6729
6730/// The declared type of `name` read as a data member of the class that lexically
6731/// owns `node`.
6732///
6733/// `None` when there is no enclosing class, when the name is not one data member
6734/// of it, or when the member's declared type does not resolve. An unknown
6735/// argument type makes the overload filter keep every candidate, which is the
6736/// honest answer for a field the index cannot type.
6737fn enclosing_member_field_arg_type(
6738    node: Node<'_>,
6739    name: &str,
6740    ctx: &ScanCtx<'_>,
6741) -> Option<CppArgType> {
6742    let owner = enclosing_context(node, ctx).owner?;
6743    let fields = ctx
6744        .visibility
6745        .visible_members_for_owner_name(ctx.file, &owner, name)
6746        .into_iter()
6747        .filter(|unit| unit.is_field())
6748        .collect::<Vec<_>>();
6749    let [field] = fields.as_slice() else {
6750        return None;
6751    };
6752    let (type_name, unit, indirection) =
6753        field_declared_type_binding(&ctx.analyzer, ctx.visibility, ctx.file, field)?;
6754    Some(CppArgType {
6755        name: type_name,
6756        unit,
6757        indirection,
6758        pointee_const: false,
6759    })
6760}
6761
6762/// Record a *non-call* reference to a free function used as a value: `&foo`,
6763/// `fp = foo`, `foo` passed as an argument, etc. The callee identifier of a call
6764/// `foo()` is recorded by the call_expression arm, and the function's own
6765/// declaration/definition name is not a reference.
6766fn maybe_record_free_function_value_reference(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6767    let text = node_text(node, ctx.source);
6768    if !name_matches_callable(text, &ctx.spec.member_name) {
6769        return;
6770    }
6771    if let Some(kind) = recovered_callable_declaration_kind(node, ctx) {
6772        *ctx.raw_match_count += 1;
6773        match kind {
6774            RecoveredCallableDeclarationKind::Declaration => push_declared_reference_hit(node, ctx),
6775            RecoveredCallableDeclarationKind::Definition => {
6776                push_recovered_definition_hit(node, ctx)
6777            }
6778        }
6779        return;
6780    }
6781    if is_declaration_name(node) {
6782        maybe_record_free_function_declaration_reference(node, ctx);
6783        return;
6784    }
6785    if is_call_callee_node(node) {
6786        return;
6787    }
6788    *ctx.raw_match_count += 1;
6789    if ctx.visibility.contains_named_symbol(
6790        ctx.file,
6791        text,
6792        TargetKind::FreeFunction,
6793        &ctx.spec.target,
6794    ) {
6795        push_hit(node, ctx);
6796    } else if ctx.visibility.resolve_known_non_target(
6797        ctx.file,
6798        text,
6799        TargetKind::FreeFunction,
6800        &ctx.spec.target,
6801    ) {
6802        // A qualified reference proven to a different namespace is not a match.
6803    } else {
6804        push_unproven_hit(node, ctx);
6805    }
6806}
6807
6808#[derive(Clone, Copy)]
6809enum RecoveredCallableDeclarationKind {
6810    Declaration,
6811    Definition,
6812}
6813
6814/// Recover the role of a callable name whose declaration was split by an
6815/// ERROR node. An indexed declaration range proves identity when available;
6816/// for a top-level C callable that recovery failed to range-index, same-file
6817/// name identity is sufficient because C has no function overloading. The CST
6818/// shape distinguishes a prototype from a definition. C++ parsing of
6819/// an unknown C return type can put the name under an ERROR child of the
6820/// function declarator, while call-shaped recovery puts that declarator under
6821/// an ERROR whose parent is a compound statement; only the former is admitted.
6822fn recovered_callable_declaration_kind(
6823    node: Node<'_>,
6824    ctx: &ScanCtx<'_>,
6825) -> Option<RecoveredCallableDeclarationKind> {
6826    if !matches!(node.kind(), "identifier" | "field_identifier") {
6827        return None;
6828    }
6829    let target_identity_proven =
6830        ctx.target_declaration_ranges.iter().any(|range| {
6831            range.start_byte <= node.start_byte() && node.end_byte() <= range.end_byte
6832        }) || (ctx.analyzer.reference_uses_c_semantics(ctx.file)
6833            && ctx.spec.target.is_function()
6834            && ctx.spec.target.source() == ctx.file);
6835    let mut current = ctx.ancestry.parent(node);
6836    while let Some(parent) = current {
6837        if parent.is_error() {
6838            // C files with an unknown return type can retain the real
6839            // callable name as `function_declarator > ERROR`, with the ERROR
6840            // as a named child rather than the declarator field itself.
6841            let error = parent;
6842            let Some(function) = ctx.ancestry.parent(error).filter(|function| {
6843                function.kind() == "function_declarator"
6844                    && function
6845                        .child_by_field_name("parameters")
6846                        .is_some_and(|parameters| error.end_byte() <= parameters.start_byte())
6847            }) else {
6848                current = ctx.ancestry.parent(parent);
6849                continue;
6850            };
6851            let container = ctx.ancestry.parent(function)?;
6852            let kind = match container.kind() {
6853                "declaration" => RecoveredCallableDeclarationKind::Declaration,
6854                "function_definition" => RecoveredCallableDeclarationKind::Definition,
6855                _ => return None,
6856            };
6857            return target_identity_proven.then_some(kind);
6858        }
6859        if parent.kind() == "function_declarator" {
6860            let error = ctx
6861                .ancestry
6862                .parent(parent)
6863                .filter(|parent| parent.is_error())?;
6864            let declarator = parent.child_by_field_name("declarator")?;
6865            if declarator.start_byte() > node.start_byte()
6866                || node.end_byte() > declarator.end_byte()
6867            {
6868                return None;
6869            }
6870            let container = ctx.ancestry.parent(error)?;
6871            let kind = match container.kind() {
6872                "declaration" => RecoveredCallableDeclarationKind::Declaration,
6873                "function_definition" => RecoveredCallableDeclarationKind::Definition,
6874                _ => return None,
6875            };
6876            return target_identity_proven.then_some(kind);
6877        }
6878        if parent.is_error() {
6879            current = ctx.ancestry.parent(parent);
6880            continue;
6881        }
6882        if matches!(
6883            parent.kind(),
6884            "translation_unit" | "function_definition" | "compound_statement"
6885        ) {
6886            return None;
6887        }
6888        current = ctx.ancestry.parent(parent);
6889    }
6890    None
6891}
6892
6893fn maybe_record_free_function_declaration_reference(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6894    if !ctx.spec.callable_has_definition_body {
6895        return;
6896    }
6897    let text = node_text(node, ctx.source);
6898    if !name_matches_callable(text, &ctx.spec.member_name) {
6899        return;
6900    }
6901    let mut declaration = ctx.ancestry.parent(node);
6902    while let Some(candidate) = declaration {
6903        if candidate.kind() == "function_definition" {
6904            return;
6905        }
6906        if candidate.kind() == "declaration" {
6907            break;
6908        }
6909        declaration = ctx.ancestry.parent(candidate);
6910    }
6911    if declaration.is_none() {
6912        return;
6913    }
6914    let linked_declaration = ctx
6915        .visibility
6916        .named_candidates(ctx.file, text, TargetKind::FreeFunction)
6917        .into_iter()
6918        .find(|candidate| {
6919            candidate.source() == ctx.file
6920                && candidate.is_function()
6921                && (!ctx.target_group.contains(candidate)
6922                    || candidate.source() == ctx.spec.target.source())
6923                && ctx.analyzer.ranges(candidate).iter().any(|range| {
6924                    range.start_byte <= node.start_byte() && node.end_byte() <= range.end_byte
6925                })
6926                && (candidate.source() == ctx.spec.target.source()
6927                    && candidate.fq_name() == ctx.spec.target.fq_name()
6928                    && candidate.signature() == ctx.spec.target.signature()
6929                    || cpp_callable_definitions_share_identity_evidence_with_visibility(
6930                        &ctx.analyzer,
6931                        ctx.visibility,
6932                        candidate,
6933                        &ctx.spec.target,
6934                    ))
6935                && callable_arity_matches_target(candidate, node, ctx)
6936        });
6937    if linked_declaration.is_none() {
6938        return;
6939    }
6940    *ctx.raw_match_count += 1;
6941    push_declaration_reference_hit(node, ctx);
6942}
6943
6944fn maybe_record_free_function_definition_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6945    let Some(function) = function_definition_name_node(node) else {
6946        return;
6947    };
6948    let text = node_text(function, ctx.source);
6949    if !name_matches_callable(text, &ctx.spec.member_name) {
6950        return;
6951    }
6952    *ctx.raw_match_count += 1;
6953    if !function_definition_signature_matches_target(node, ctx) {
6954        return;
6955    }
6956    match definition_name_target_resolution(function, TargetKind::FreeFunction, ctx) {
6957        DefinitionNameTargetResolution::Target => push_definition_hit(function, ctx),
6958        DefinitionNameTargetResolution::KnownNonTarget => {
6959            // A definition in another explicit namespace is a proven non-match.
6960        }
6961        DefinitionNameTargetResolution::Unresolved => push_unproven_definition_hit(function, ctx),
6962    }
6963}
6964
6965fn maybe_record_method_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
6966    if node.kind() == "preproc_arg" {
6967        maybe_record_function_macro_replacement_method_hits(node, ctx);
6968        return;
6969    }
6970    if node.kind() == "using_declaration" {
6971        maybe_record_using_callable_hit(node, ctx);
6972        return;
6973    }
6974    if has_ancestor_kind(node, "using_declaration") {
6975        return;
6976    }
6977    if node.kind() == "function_definition" {
6978        maybe_record_method_definition_hit(node, ctx);
6979        return;
6980    }
6981    if is_declaration_name(node) {
6982        return;
6983    }
6984    if let Some(member) = recovered_direct_initializer_qualified_callable(node) {
6985        maybe_record_qualified_method_value_hit(node, member, ctx);
6986        return;
6987    }
6988    if let Some(value) = qualified_callable_value(node) {
6989        maybe_record_qualified_method_value_hit(value.qualified, value.member, ctx);
6990        return;
6991    }
6992    if let Some(call) = recovered_relational_template_member_call(node) {
6993        maybe_record_recovered_relational_template_method_hit(call, ctx);
6994        return;
6995    }
6996    if node.kind() != "call_expression" {
6997        return;
6998    }
6999    if let Some((receiver, operator)) = explicit_operator_call(node) {
7000        let text = node_text(operator, ctx.source);
7001        if !name_matches_callable(text, &ctx.spec.member_name) {
7002            return;
7003        }
7004        *ctx.raw_match_count += 1;
7005        if let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) {
7006            match ctx
7007                .visibility
7008                .call_arity_evidence(ctx.file, node, ctx.source)
7009                .accepts(expected)
7010            {
7011                Some(true) => {}
7012                Some(false) => return,
7013                None => {
7014                    push_unproven_hit(operator, ctx);
7015                    return;
7016                }
7017            }
7018        }
7019        let arity = ctx
7020            .visibility
7021            .call_arity_evidence(ctx.file, node, ctx.source)
7022            .exact();
7023        record_explicit_receiver_method_hit(receiver, operator, arity, ctx);
7024        return;
7025    }
7026    let Some(function) = node
7027        .child_by_field_name("function")
7028        .or_else(|| node.named_child(0))
7029    else {
7030        return;
7031    };
7032    if !callable_node_matches(function, &ctx.spec.member_name, ctx.source) {
7033        return;
7034    }
7035    if function.kind() == "identifier"
7036        && ctx
7037            .local_shadows
7038            .is_shadowed(node_text(function, ctx.source))
7039    {
7040        return;
7041    }
7042    *ctx.raw_match_count += 1;
7043    if let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) {
7044        match ctx
7045            .visibility
7046            .call_arity_evidence(ctx.file, node, ctx.source)
7047            .accepts(expected)
7048        {
7049            Some(true) => {}
7050            Some(false) => return,
7051            None => {
7052                push_unproven_hit(function_terminal_node(function), ctx);
7053                return;
7054            }
7055        }
7056    }
7057    if !method_call_may_target(node, ctx) {
7058        return;
7059    }
7060    if is_structurally_qualified(function) {
7061        match qualified_owner_resolution(function, ctx) {
7062            QualifiedOwnerResolution::Target => {
7063                push_hit(function_terminal_node(function), ctx);
7064            }
7065            QualifiedOwnerResolution::NonTarget => {}
7066            QualifiedOwnerResolution::Unresolved => {
7067                push_unproven_hit(function_terminal_node(function), ctx);
7068            }
7069        }
7070        return;
7071    }
7072    match call_function_target_resolution(function, ctx) {
7073        MethodReceiverTargetResolution::Target
7074            if call_function_has_direct_self_receiver(
7075                function,
7076                ctx.analyzer.reference_uses_c_semantics(ctx.file),
7077            ) =>
7078        {
7079            push_self_receiver_hit(function_terminal_node(function), ctx);
7080        }
7081        MethodReceiverTargetResolution::Target => {
7082            push_hit(function_terminal_node(function), ctx);
7083        }
7084        MethodReceiverTargetResolution::NonTarget | MethodReceiverTargetResolution::Ambiguous => {}
7085        // A bare `m()` whose name resolves through the enclosing class's base hierarchy to
7086        // the target member declared on a base is a genuine external usage of that inherited
7087        // base member (e.g. `Derived::run` calling inherited `Base::value`), so it is an
7088        // ordinary Reference hit -- not a same-type self call. Checked before the self-owner
7089        // arm because `same_owner_context` also accepts this inherited case.
7090        MethodReceiverTargetResolution::Missing
7091            if inherited_target_owner_context(function, ctx) =>
7092        {
7093            push_hit(function_terminal_node(function), ctx);
7094        }
7095        MethodReceiverTargetResolution::Missing
7096            if (matches!(function.kind(), "identifier" | "template_function")
7097                || call_function_has_direct_self_receiver(
7098                    function,
7099                    ctx.analyzer.reference_uses_c_semantics(ctx.file),
7100                ))
7101                && (same_owner_context(function, ctx)
7102                    || out_of_line_target_owner_context(function, ctx)) =>
7103        {
7104            push_self_receiver_hit(function_terminal_node(function), ctx);
7105        }
7106        MethodReceiverTargetResolution::Missing
7107            if function.kind() == "identifier"
7108                && resolves_to_lexical_free_function(function, ctx) =>
7109        {
7110            // A visible namespace/free function is a proven negative once the
7111            // enclosing structured owner and its hierarchy contain no such member.
7112        }
7113        MethodReceiverTargetResolution::Missing
7114            if !receiver_has_known_non_target(function, ctx)
7115                && !known_non_target_owner_context(function, ctx) =>
7116        {
7117            push_unproven_hit(function_terminal_node(function), ctx);
7118        }
7119        MethodReceiverTargetResolution::Missing => {}
7120    }
7121}
7122
7123/// Report member calls written inside a function-like macro's replacement.
7124///
7125/// Tree-sitter keeps the whole replacement of `#define NAME(a) ...` as one
7126/// opaque `preproc_arg`, so the ordinary member-call path never sees the calls
7127/// it contains (#2549). The resolver's shared sentinel parse recovers them as
7128/// structure, and every hit is reported at the bytes the member spells inside
7129/// that token.
7130fn maybe_record_function_macro_replacement_method_hits(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
7131    let Some(definition) = ctx.ancestry.parent(node).filter(|parent| {
7132        parent.kind() == "preproc_function_def"
7133            && parent
7134                .child_by_field_name("value")
7135                .is_some_and(|value| same_node(value, node))
7136    }) else {
7137        return;
7138    };
7139    let Some(body) = ctx
7140        .visibility
7141        .function_macro_replacement_body(ctx.file, definition, ctx.source)
7142    else {
7143        return;
7144    };
7145    let Some(statements) = body.statements() else {
7146        return;
7147    };
7148    // Collect the candidate calls before typing anything: a replacement that
7149    // never names the queried member must not pay for its declarations.
7150    let mut candidates = Vec::new();
7151    let mut stack = vec![statements];
7152    while let Some(current) = stack.pop() {
7153        push_named_children_reversed(current, &mut stack);
7154        if current.kind() != "call_expression" {
7155            continue;
7156        }
7157        let Some(function) = current
7158            .child_by_field_name("function")
7159            .filter(|function| function.kind() == "field_expression")
7160        else {
7161            continue;
7162        };
7163        let Some(member) = function.child_by_field_name("field") else {
7164            continue;
7165        };
7166        if !name_matches_callable(node_text(member, &body.source), &ctx.spec.member_name) {
7167            continue;
7168        }
7169        let Some(receiver) = function
7170            .child_by_field_name("argument")
7171            .or_else(|| function.child_by_field_name("object"))
7172            .or_else(|| function.named_child(0))
7173        else {
7174            continue;
7175        };
7176        candidates.push((current, member, receiver));
7177    }
7178    if candidates.is_empty() {
7179        return;
7180    }
7181    let Some(replacement_start) =
7182        function_macro_replacement_span(definition, ctx.source).map(|span| span.start)
7183    else {
7184        return;
7185    };
7186    let locals = macro_replacement_local_receivers(statements, &body, ctx);
7187    for (current, member, receiver) in candidates {
7188        if *ctx.limit_exceeded {
7189            return;
7190        }
7191        let range = body.file_range(member, replacement_start);
7192        debug_assert_eq!(
7193            ctx.source.get(range.clone()),
7194            Some(node_text(member, &body.source)),
7195            "macro replacement member range must spell the member name"
7196        );
7197        *ctx.raw_match_count += 1;
7198        // The replacement's own macro environment is the one at the definition,
7199        // not at the sentinel offsets the recovered call carries.
7200        let arity_evidence = ctx.visibility.call_arity_evidence_at(
7201            ctx.file,
7202            current,
7203            &body.source,
7204            definition.start_byte(),
7205        );
7206        if let Some(expected) = ctx.spec.callable_arity_at(range.start) {
7207            match arity_evidence.accepts(expected) {
7208                Some(true) => {}
7209                Some(false) => continue,
7210                None => {
7211                    push_unproven_reference_hit_range(node, range.start, range.end, ctx);
7212                    continue;
7213                }
7214            }
7215        }
7216        let declaring_owner = match macro_replacement_receiver(receiver, &body, &locals, node, ctx)
7217        {
7218            MacroReplacementReceiver::Parameter => {
7219                if target_member_is_visible_candidate(ctx) {
7220                    push_unproven_reference_hit_range(node, range.start, range.end, ctx);
7221                }
7222                continue;
7223            }
7224            MacroReplacementReceiver::Unknown => continue,
7225            MacroReplacementReceiver::Units(units) => {
7226                declaring_owner_from_receiver_units(units, range.start, arity_evidence.exact(), ctx)
7227            }
7228        };
7229        match declaring_owner_target_resolution(declaring_owner, range.start, ctx) {
7230            MethodReceiverTargetResolution::Target => {
7231                push_reference_hit_range(node, range.start, range.end, ctx);
7232            }
7233            MethodReceiverTargetResolution::Missing => {
7234                push_unproven_reference_hit_range(node, range.start, range.end, ctx);
7235            }
7236            MethodReceiverTargetResolution::NonTarget
7237            | MethodReceiverTargetResolution::Ambiguous => {}
7238        }
7239    }
7240}
7241
7242enum MacroReplacementReceiver {
7243    /// The receiver is one of the macro's parameters. Its type is supplied by
7244    /// each invocation, so a member call on it can never be proven here.
7245    Parameter,
7246    /// The receiver's declared type resolved to these units.
7247    Units(Vec<CodeUnit>),
7248    /// The receiver has a shape this path does not type.
7249    Unknown,
7250}
7251
7252fn macro_replacement_receiver(
7253    receiver: Node<'_>,
7254    body: &ParsedReplacementBody,
7255    locals: &HashMap<String, Option<CodeUnit>>,
7256    anchor: Node<'_>,
7257    ctx: &ScanCtx<'_>,
7258) -> MacroReplacementReceiver {
7259    let mut current = receiver;
7260    while matches!(
7261        current.kind(),
7262        "parenthesized_expression" | "pointer_expression"
7263    ) {
7264        let Some(inner) = current
7265            .child_by_field_name("argument")
7266            .or_else(|| current.named_child(0))
7267        else {
7268            return MacroReplacementReceiver::Unknown;
7269        };
7270        current = inner;
7271    }
7272    if !matches!(current.kind(), "identifier" | "field_identifier") {
7273        return MacroReplacementReceiver::Unknown;
7274    }
7275    let name = node_text(current, &body.source);
7276    if body.parameters.iter().any(|parameter| parameter == name) {
7277        return MacroReplacementReceiver::Parameter;
7278    }
7279    if let Some(local) = locals.get(name) {
7280        return match local {
7281            Some(unit) => MacroReplacementReceiver::Units(vec![unit.clone()]),
7282            None => MacroReplacementReceiver::Unknown,
7283        };
7284    }
7285    // Neither a parameter nor a replacement-local: an ordinary name the macro
7286    // definition site sees, resolved exactly as the ordinary receiver path
7287    // resolves a bare identifier.
7288    let global_fields = ctx
7289        .visibility
7290        .visible_identifier_candidates(ctx.file, name)
7291        .filter(|unit| has_persisted_global_field_identity(unit) && unit.identifier() == name)
7292        .collect::<Vec<_>>();
7293    if !global_fields.is_empty() {
7294        return MacroReplacementReceiver::Units(receiver_units_from_declared_fields(
7295            global_fields,
7296            anchor,
7297            ctx,
7298        ));
7299    }
7300    MacroReplacementReceiver::Units(
7301        ctx.visibility
7302            .resolve_type(ctx.file, name)
7303            .into_iter()
7304            .collect(),
7305    )
7306}
7307
7308/// Type the locals a macro replacement declares, keyed by declared name.
7309///
7310/// `Catch::AssertionHandler h(expr); h.handleExpr(expr);` is the shape this
7311/// serves: the receiver's type is stated inside the replacement itself. A name
7312/// whose declared type does not resolve is kept with no unit, so a call on it
7313/// stays silent instead of falling through to file-scope name lookup.
7314fn macro_replacement_local_receivers(
7315    statements: Node<'_>,
7316    body: &ParsedReplacementBody,
7317    ctx: &ScanCtx<'_>,
7318) -> HashMap<String, Option<CodeUnit>> {
7319    let mut locals = HashMap::default();
7320    let mut stack = vec![statements];
7321    while let Some(current) = stack.pop() {
7322        push_named_children_reversed(current, &mut stack);
7323        if current.kind() != "declaration" {
7324            continue;
7325        }
7326        let Some(type_node) = current
7327            .child_by_field_name("type")
7328            .or_else(|| first_type_child(current))
7329        else {
7330            continue;
7331        };
7332        let unit = macro_replacement_declared_unit(type_node, body, ctx);
7333        let mut cursor = current.walk();
7334        for child in current.named_children(&mut cursor) {
7335            let declarator = if child.kind() == "init_declarator" {
7336                child.child_by_field_name("declarator")
7337            } else {
7338                is_declarator_node(child).then_some(child)
7339            };
7340            let Some(name) =
7341                declarator.and_then(|declarator| extract_variable_name(declarator, &body.source))
7342            else {
7343                continue;
7344            };
7345            locals.insert(name, unit.clone());
7346        }
7347    }
7348    locals
7349}
7350
7351fn macro_replacement_declared_unit(
7352    type_node: Node<'_>,
7353    body: &ParsedReplacementBody,
7354    ctx: &ScanCtx<'_>,
7355) -> Option<CodeUnit> {
7356    let name = normalize_cpp_type_name(node_text(type_node, &body.source));
7357    let unit = match ctx
7358        .visibility
7359        .resolve_type_node_result(ctx.file, type_node, &body.source)
7360    {
7361        Ok(Some(unit)) => Some(unit),
7362        Ok(None) => ctx
7363            .visibility
7364            .canonical_type_for_reference(ctx.file, &name)
7365            .or_else(|| ctx.visibility.resolve_type(ctx.file, &name)),
7366        Err(_) => None,
7367    }?;
7368    canonical_receiver_unit(&unit, ctx)
7369}
7370
7371/// Whether the queried member is a candidate this file can see.
7372///
7373/// A macro parameter receiver has no type at the definition, so a member call
7374/// on it is at most unproven. Requiring the target to be visible here keeps a
7375/// same-named member of an unrelated translation unit out of the result.
7376fn target_member_is_visible_candidate(ctx: &ScanCtx<'_>) -> bool {
7377    ctx.visibility
7378        .visible_identifier_candidates(ctx.file, &ctx.spec.member_name)
7379        .any(|candidate| same_visible_symbol(candidate, &ctx.spec.target))
7380}
7381
7382fn maybe_record_recovered_relational_template_method_hit(
7383    call: RecoveredRelationalTemplateMemberCall<'_>,
7384    ctx: &mut ScanCtx<'_>,
7385) {
7386    if !callable_node_matches(call.member, &ctx.spec.member_name, ctx.source) {
7387        return;
7388    }
7389    *ctx.raw_match_count += 1;
7390    if !ctx
7391        .visibility
7392        .callable_is_template_declaration(&ctx.analyzer, &ctx.spec.target)
7393        || ctx
7394            .spec
7395            .callable_arity_at(call.member.start_byte())
7396            .is_some_and(|arity| !arity.accepts(call.arity))
7397    {
7398        return;
7399    }
7400    record_explicit_receiver_method_hit(call.receiver, call.member, Some(call.arity), ctx);
7401}
7402
7403fn record_explicit_receiver_method_hit(
7404    receiver: Node<'_>,
7405    member: Node<'_>,
7406    arity: Option<usize>,
7407    ctx: &mut ScanCtx<'_>,
7408) {
7409    match explicit_receiver_target_resolution(receiver, arity, ctx) {
7410        MethodReceiverTargetResolution::Target
7411            if receiver_is_self_like(
7412                receiver,
7413                ctx.analyzer.reference_uses_c_semantics(ctx.file),
7414            ) =>
7415        {
7416            push_self_receiver_hit(member, ctx);
7417        }
7418        MethodReceiverTargetResolution::Target => push_hit(member, ctx),
7419        MethodReceiverTargetResolution::Missing => push_unproven_hit(member, ctx),
7420        MethodReceiverTargetResolution::NonTarget | MethodReceiverTargetResolution::Ambiguous => {}
7421    }
7422}
7423
7424fn recovered_direct_initializer_qualified_callable(node: Node<'_>) -> Option<Node<'_>> {
7425    if node.kind() != "qualified_identifier" {
7426        return None;
7427    }
7428    let parameter = node
7429        .parent()
7430        .filter(|parent| parent.kind() == "parameter_declaration")?;
7431    let parameter_declarator = parameter.child_by_field_name("declarator")?;
7432    // Tree-sitter recovers `Value value(Owner::method(arg));` as a function
7433    // declaration whose sole pseudo-parameter has `Owner::method` as its type
7434    // and `(arg)` as an abstract function declarator. Ordinary qualified
7435    // parameter types have named/pointer/reference declarators instead.
7436    if parameter.child_by_field_name("type") != Some(node)
7437        || parameter_declarator.kind() != "abstract_function_declarator"
7438    {
7439        return None;
7440    }
7441    let parameter_list = parameter
7442        .parent()
7443        .filter(|parent| parent.kind() == "parameter_list")?;
7444    if parameter_list.named_child_count() != 1 {
7445        return None;
7446    }
7447    let function_declarator = parameter_list
7448        .parent()
7449        .filter(|parent| parent.kind() == "function_declarator")?;
7450    if function_declarator
7451        .child_by_field_name("declarator")
7452        .is_none_or(|declarator| declarator.kind() != "identifier")
7453        || function_declarator
7454            .parent()
7455            .is_none_or(|parent| parent.kind() != "declaration")
7456    {
7457        return None;
7458    }
7459    node.child_by_field_name("name")
7460}
7461
7462fn maybe_record_using_callable_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
7463    let Some(imported) = ordinary_using_declaration_type_node(node) else {
7464        return;
7465    };
7466    if !callable_node_matches(imported, &ctx.spec.member_name, ctx.source) {
7467        return;
7468    }
7469    let Some(target_owner) = ctx.spec.owner.as_ref() else {
7470        return;
7471    };
7472    *ctx.raw_match_count += 1;
7473    let owner_resolution = qualified_owner_components(imported, ctx.source)
7474        .map(|qualified| {
7475            let lexical_scope = match enclosing_lexical_scope_components(
7476                imported,
7477                &ctx.analyzer,
7478                ctx.visibility,
7479                ctx.file,
7480                ctx.source,
7481            ) {
7482                LexicalScopeResolution::Resolved(scope) => scope,
7483                LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
7484                LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
7485            };
7486            ctx.visibility.resolve_type_components_lexically(
7487                &ctx.analyzer,
7488                ctx.file,
7489                &qualified.names,
7490                qualified.global,
7491                &lexical_scope,
7492            )
7493        })
7494        .unwrap_or(LexicalTypeResolution::Missing);
7495    let matches_target_owner = matches!(
7496        owner_resolution,
7497        LexicalTypeResolution::Resolved {
7498            ref unit,
7499            ref candidates,
7500            ..
7501        } if same_visible_symbol(unit, target_owner)
7502            || candidates
7503                .iter()
7504                .any(|candidate| same_visible_symbol(candidate, target_owner))
7505    );
7506    if !matches_target_owner {
7507        match owner_resolution {
7508            LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => {
7509                push_unproven_hit(imported, ctx);
7510            }
7511            LexicalTypeResolution::Resolved { .. } => {}
7512        }
7513        return;
7514    }
7515    match visible_target_callable_member_resolution(target_owner, ctx) {
7516        VisibleTargetCallableMemberResolution::Target => push_hit(imported, ctx),
7517        VisibleTargetCallableMemberResolution::NonCallable => {}
7518        VisibleTargetCallableMemberResolution::Unresolved => push_unproven_hit(imported, ctx),
7519    }
7520}
7521
7522enum VisibleTargetCallableMemberResolution {
7523    Target,
7524    NonCallable,
7525    Unresolved,
7526}
7527
7528fn visible_target_callable_member_resolution(
7529    owner: &CodeUnit,
7530    ctx: &ScanCtx<'_>,
7531) -> VisibleTargetCallableMemberResolution {
7532    match ctx
7533        .visibility
7534        .visible_member_for_owner_name(ctx.file, owner, &ctx.spec.member_name)
7535    {
7536        VisibleMemberResolution::Callable(candidates)
7537            if candidates.iter().all(|candidate| {
7538                ctx.target_group.contains(candidate)
7539                    || ctx
7540                        .target_group
7541                        .iter()
7542                        .any(|target| same_visible_symbol(candidate, target))
7543            }) =>
7544        {
7545            VisibleTargetCallableMemberResolution::Target
7546        }
7547        VisibleMemberResolution::NonCallable => VisibleTargetCallableMemberResolution::NonCallable,
7548        VisibleMemberResolution::Callable(_)
7549        | VisibleMemberResolution::AmbiguousKind
7550        | VisibleMemberResolution::Missing => VisibleTargetCallableMemberResolution::Unresolved,
7551    }
7552}
7553
7554fn resolves_to_lexical_free_function(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
7555    let name = node_text(node, ctx.source);
7556    let namespace = enclosing_namespace_components(node, ctx.source).join(".");
7557    let key = (namespace.clone(), name.to_string());
7558    if let Some(resolved) = ctx.lexical_free_function_cache.borrow().get(&key).copied() {
7559        return resolved;
7560    }
7561    let resolved = ctx
7562        .visibility
7563        .visible_identifier_candidates(ctx.file, name)
7564        .any(|unit| {
7565            unit.is_function()
7566                && type_owner_of(&ctx.analyzer, unit).is_none()
7567                && unit.package_name() == namespace
7568        });
7569    ctx.lexical_free_function_cache
7570        .borrow_mut()
7571        .insert(key, resolved);
7572    resolved
7573}
7574
7575fn maybe_record_qualified_method_value_hit(
7576    qualified: Node<'_>,
7577    member: Node<'_>,
7578    ctx: &mut ScanCtx<'_>,
7579) {
7580    if !name_matches_callable(node_text(member, ctx.source), &ctx.spec.member_name) {
7581        return;
7582    }
7583    *ctx.raw_match_count += 1;
7584    let resolution =
7585        qualified_callable_value_resolution(qualified, node_text(member, ctx.source), ctx);
7586    match resolution {
7587        LexicalCallableValueResolution::Type(resolved_owner) => {
7588            let Some(owner) = ctx.spec.owner.as_ref() else {
7589                push_unproven_hit(member, ctx);
7590                return;
7591            };
7592            if !receiver_owner_matches_target(&resolved_owner, owner, member.start_byte(), ctx) {
7593                if same_visible_symbol(&resolved_owner, owner) {
7594                    push_unproven_hit(member, ctx);
7595                }
7596                return;
7597            }
7598            // An explicitly qualified method value remains an external
7599            // reference even when its owner is the enclosing class.
7600            match visible_target_callable_member_resolution(owner, ctx) {
7601                VisibleTargetCallableMemberResolution::Target => push_hit(member, ctx),
7602                VisibleTargetCallableMemberResolution::NonCallable => {}
7603                VisibleTargetCallableMemberResolution::Unresolved => {
7604                    push_unproven_hit(member, ctx);
7605                }
7606            }
7607        }
7608        LexicalCallableValueResolution::FreeFunction(_) => {}
7609        LexicalCallableValueResolution::Ambiguous | LexicalCallableValueResolution::Missing => {
7610            push_unproven_hit(member, ctx);
7611        }
7612    }
7613}
7614
7615fn qualified_callable_value_resolution(
7616    qualified: Node<'_>,
7617    member_name: &str,
7618    ctx: &ScanCtx<'_>,
7619) -> LexicalCallableValueResolution {
7620    let Some((owner_components, global)) =
7621        qualified_callable_owner_components(qualified, ctx.source)
7622    else {
7623        return LexicalCallableValueResolution::Missing;
7624    };
7625    let lexical_scope = if global {
7626        Vec::new()
7627    } else {
7628        match enclosing_lexical_scope_components(
7629            qualified,
7630            &ctx.analyzer,
7631            ctx.visibility,
7632            ctx.file,
7633            ctx.source,
7634        ) {
7635            LexicalScopeResolution::Resolved(scope) => scope,
7636            LexicalScopeResolution::Ambiguous => {
7637                return LexicalCallableValueResolution::Ambiguous;
7638            }
7639            LexicalScopeResolution::Missing => return LexicalCallableValueResolution::Missing,
7640        }
7641    };
7642    if let Some(target_owner) = ctx.spec.owner.as_ref()
7643        && let LexicalTypeResolution::Resolved { unit, .. } =
7644            resolve_type_components_lexically_at_for_target_with_scope_cache(
7645                qualified,
7646                &owner_components,
7647                global,
7648                &ctx.analyzer,
7649                ctx.visibility,
7650                &ctx.ordinary_type_imports,
7651                ctx.file,
7652                ctx.source,
7653                target_owner,
7654                false,
7655                Some(&ctx.lexical_scope_cache),
7656            )
7657    {
7658        return LexicalCallableValueResolution::Type(unit);
7659    }
7660    ctx.visibility.resolve_callable_value_components_lexically(
7661        &ctx.analyzer,
7662        ctx.file,
7663        &owner_components,
7664        member_name,
7665        global,
7666        &lexical_scope,
7667    )
7668}
7669
7670fn method_call_may_target(call: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
7671    let Some(owner) = ctx.spec.owner.as_ref() else {
7672        return true;
7673    };
7674    if ctx.spec.param_types.is_none() {
7675        return true;
7676    }
7677    let candidates = ctx
7678        .visibility
7679        .visible_members_for_owner_name(ctx.file, owner, &ctx.spec.member_name)
7680        .into_iter()
7681        .filter(|unit| unit.is_function())
7682        .cloned()
7683        .collect::<Vec<_>>();
7684    callable_candidates_may_match_target(call, candidates, ctx)
7685}
7686
7687fn maybe_record_method_definition_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
7688    let Some(function) = function_definition_name_node(node) else {
7689        return;
7690    };
7691    if !callable_node_matches(function, &ctx.spec.member_name, ctx.source) {
7692        return;
7693    }
7694    *ctx.raw_match_count += 1;
7695    if !function_definition_signature_matches_target(node, ctx) {
7696        return;
7697    }
7698    if node_inside_target_declaration(function, ctx) {
7699        return;
7700    }
7701    if is_structurally_qualified(function) {
7702        match qualified_owner_resolution(function, ctx) {
7703            QualifiedOwnerResolution::Target => push_definition_hit(function, ctx),
7704            QualifiedOwnerResolution::NonTarget => {}
7705            QualifiedOwnerResolution::Unresolved => push_unproven_definition_hit(function, ctx),
7706        }
7707        return;
7708    }
7709    match definition_name_target_resolution(function, TargetKind::Method, ctx) {
7710        DefinitionNameTargetResolution::Target => push_definition_hit(function, ctx),
7711        DefinitionNameTargetResolution::KnownNonTarget => {
7712            // A method definition for another visible owner is a proven non-match.
7713        }
7714        DefinitionNameTargetResolution::Unresolved
7715            if known_non_target_owner_context(function, ctx) => {}
7716        DefinitionNameTargetResolution::Unresolved => push_unproven_definition_hit(function, ctx),
7717    }
7718}
7719
7720pub(super) fn node_inside_target_declaration(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
7721    let node_range = brokk_bifrost_core::analyzer::tree_walk::node_range(node);
7722    ctx.target_declaration_ranges
7723        .iter()
7724        .any(|range| range.contains(&node_range))
7725}
7726
7727fn explicit_operator_call(node: Node<'_>) -> Option<(Node<'_>, Node<'_>)> {
7728    let mut receiver = None;
7729    let mut cursor = node.walk();
7730    for child in node.named_children(&mut cursor) {
7731        if child.kind() == "argument_list" {
7732            continue;
7733        }
7734        if let Some(operator) = first_descendant_of_kind(child, "operator_name") {
7735            return receiver.map(|receiver| (receiver, operator));
7736        }
7737        if receiver.is_none() {
7738            receiver = Some(child);
7739        }
7740    }
7741    None
7742}
7743
7744/// Return the name node of a C++ function definition's declarator.
7745pub fn function_definition_name_node(node: Node<'_>) -> Option<Node<'_>> {
7746    if node.kind() != "function_definition" {
7747        return None;
7748    }
7749    node.child_by_field_name("declarator")
7750        .and_then(declarator_name_node)
7751}
7752
7753fn function_definition_owner_lookup_node(node: Node<'_>) -> Option<Node<'_>> {
7754    function_definition_name_node(node)
7755}
7756
7757fn function_definition_signature_matches_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
7758    let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) else {
7759        return true;
7760    };
7761    let Some(candidate) = canonical_callable_at_node(
7762        node,
7763        &ctx.analyzer,
7764        ctx.visibility,
7765        ctx.file,
7766        ctx.source,
7767        ctx.spec.kind,
7768    ) else {
7769        return false;
7770    };
7771    let Some(actual_arity) = cpp_callable_arity(&ctx.analyzer, &candidate) else {
7772        return false;
7773    };
7774    if !callable_arity_matches(expected, actual_arity) {
7775        return false;
7776    }
7777    ctx.spec.param_types.as_ref().is_none_or(|expected| {
7778        cpp_callable_parameter_types(&ctx.analyzer, &candidate)
7779            .is_some_and(|actual| actual == *expected)
7780    })
7781}
7782
7783fn callable_arity_matches_target(candidate: &CodeUnit, node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
7784    let Some(expected) = ctx.spec.callable_arity_at(node.start_byte()) else {
7785        return true;
7786    };
7787    cpp_callable_arity(&ctx.analyzer, candidate)
7788        .is_some_and(|actual| callable_arity_matches(expected, actual))
7789}
7790
7791fn callable_arity_matches(
7792    expected: brokk_bifrost_core::analyzer::model::CallableArity,
7793    actual: brokk_bifrost_core::analyzer::model::CallableArity,
7794) -> bool {
7795    expected.accepts(actual.total())
7796}
7797
7798fn canonical_callable_at_node(
7799    node: Node<'_>,
7800    analyzer: &CppGraphSource<'_>,
7801    visibility: &VisibilityIndex<'_>,
7802    file: &ProjectFile,
7803    source: &str,
7804    kind: TargetKind,
7805) -> Option<CodeUnit> {
7806    let name = callable_name_node(node)?;
7807    let name_range = (name.start_byte(), name.end_byte());
7808    let name_text = node_text(name, source);
7809    for candidate in visibility.named_candidates(file, name_text, kind) {
7810        if candidate.source() != file || !candidate.is_function() {
7811            continue;
7812        }
7813        let Some(occurrences) = analyzer.declaration_source_occurrences(&candidate) else {
7814            continue;
7815        };
7816        for occurrence in occurrences {
7817            if occurrence
7818                .name_range
7819                .is_some_and(|range| (range.start_byte, range.end_byte) == name_range)
7820            {
7821                return Some(candidate);
7822            }
7823        }
7824    }
7825    None
7826}
7827
7828fn callable_name_node(node: Node<'_>) -> Option<Node<'_>> {
7829    let name = if node.kind() == "function_definition" {
7830        function_definition_name_node(node)?
7831    } else {
7832        node.child_by_field_name("declarator")
7833            .and_then(declarator_name_node)?
7834    };
7835    Some(function_terminal_node(name))
7836}
7837
7838fn callable_node_matches(node: Node<'_>, expected: &str, source: &str) -> bool {
7839    name_matches_callable(node_text(function_terminal_node(node), source), expected)
7840}
7841
7842enum DefinitionNameTargetResolution {
7843    Target,
7844    KnownNonTarget,
7845    Unresolved,
7846}
7847
7848fn definition_name_target_resolution(
7849    function: Node<'_>,
7850    target_kind: TargetKind,
7851    ctx: &ScanCtx<'_>,
7852) -> DefinitionNameTargetResolution {
7853    let candidates = definition_name_candidates(function, ctx);
7854    if candidates
7855        .iter()
7856        .filter(|name| target_kind != TargetKind::Method || name.contains("::"))
7857        .any(|name| {
7858            ctx.visibility
7859                .contains_named_symbol(ctx.file, name, target_kind, &ctx.spec.target)
7860        })
7861    {
7862        DefinitionNameTargetResolution::Target
7863    } else if candidates.iter().any(|name| {
7864        ctx.visibility
7865            .resolve_known_non_target(ctx.file, name, target_kind, &ctx.spec.target)
7866    }) {
7867        DefinitionNameTargetResolution::KnownNonTarget
7868    } else {
7869        DefinitionNameTargetResolution::Unresolved
7870    }
7871}
7872
7873fn definition_name_candidates(function: Node<'_>, ctx: &ScanCtx<'_>) -> Vec<String> {
7874    let raw = normalize_cpp_reference_text(node_text(function, ctx.source));
7875    if raw.is_empty() {
7876        return Vec::new();
7877    }
7878    let Some(namespace) = enclosing_namespace_context(function, ctx.source) else {
7879        return vec![raw];
7880    };
7881    if !raw.contains("::") {
7882        return vec![format!("{namespace}::{raw}")];
7883    }
7884    // fqname-M4: peeks at the raw first `::`-split token, including the empty
7885    // token a leading-`::` absolute reference (`::Foo::Bar`) produces (same
7886    // shape as rust's `rust_reference_looks_external`); the shared structured
7887    // splitter filters empty segments, which would shift "which token is
7888    // first" for that one lead-`::` shape and is not proven equivalent here.
7889    if raw
7890        .split("::")
7891        .next()
7892        .is_some_and(|head| head != namespace && !namespace.ends_with(&format!("::{head}")))
7893    {
7894        vec![format!("{namespace}::{raw}"), raw]
7895    } else {
7896        vec![raw]
7897    }
7898}
7899
7900fn first_descendant_of_kind<'tree>(node: Node<'tree>, kind: &str) -> Option<Node<'tree>> {
7901    brokk_bifrost_core::analyzer::tree_walk::first_named_descendant_of_kind_inclusive(node, kind)
7902}
7903
7904/// Whether a name leaf the field scans reached sits in a value position.
7905///
7906/// Every kind those scans admit already names a value except `type_identifier`.
7907/// tree-sitter spells a non-type template argument with type syntax, so the
7908/// constant `N` in `std::array<W, N>` is a `type_identifier` exactly like the
7909/// type argument `W` beside it ([`is_type_shaped_template_argument_name`]).
7910/// Admit that leaf only where no visible type explains the spelling, which is
7911/// the order forward navigation applies before it reads the leaf in the value
7912/// namespace (#2556). Every other `type_identifier` is a type reference and
7913/// belongs to the type scan.
7914fn scan_leaf_is_value_position(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
7915    node.kind() != "type_identifier"
7916        || (is_type_shaped_template_argument_name(node)
7917            && ctx
7918                .visibility
7919                .resolve_type(ctx.file, node_text(node, ctx.source))
7920                .is_none())
7921}
7922
7923fn maybe_record_global_field_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
7924    if is_c_offsetof_member_node(node) {
7925        return;
7926    }
7927    if matches!(node.kind(), "identifier" | "field_identifier")
7928        && designated_initializer_owner(&ctx.analyzer, ctx.visibility, ctx.file, ctx.source, node)
7929            .is_some()
7930    {
7931        return;
7932    }
7933    if !matches!(
7934        node.kind(),
7935        "identifier" | "field_identifier" | "qualified_identifier" | "type_identifier"
7936    ) || !name_matches_terminal(node_text(node, ctx.source), &ctx.spec.member_name)
7937        || !scan_leaf_is_value_position(node, ctx)
7938        || is_declaration_name(node)
7939        || is_member_field_own_declarator(node, ctx)
7940        || is_selected_field_expression_member_descendant(node)
7941        || is_nested_in_qualified_identifier(node)
7942    {
7943        return;
7944    }
7945    *ctx.raw_match_count += 1;
7946    if global_field_resolves_to_target(node, ctx) {
7947        push_hit(node, ctx);
7948    } else if global_field_is_known_non_target(node, ctx) {
7949    } else {
7950        push_unproven_hit(node, ctx);
7951    }
7952}
7953
7954/// Whether `node` belongs to the selected-member side of any enclosing field
7955/// expression. A reference may be nested arbitrarily inside the receiver side
7956/// (for example, an argument to a call-built fluent receiver), so direct child
7957/// equality is insufficient: classify each ancestor by structured subtree
7958/// containment instead.
7959fn is_selected_field_expression_member_descendant(mut node: Node<'_>) -> bool {
7960    let candidate = node;
7961    while let Some(parent) = node.parent() {
7962        if parent.kind() == "field_expression" {
7963            if let Some(field) = parent.child_by_field_name("field")
7964                && node_is_within(field, candidate)
7965            {
7966                // The `template` disambiguator in `receiver.template f<Arg>()`
7967                // wraps the selected member in a `dependent_name` whose single
7968                // named child is the `template_*` node the plain spelling puts
7969                // directly under `field`. Unwrap it so both spellings reach the
7970                // same name/arguments split (#2196).
7971                let selected = match field.kind() {
7972                    "dependent_name" => field.named_child(0).unwrap_or(field),
7973                    _ => field,
7974                };
7975                let selected_name = match selected.kind() {
7976                    "template_method" | "template_function" | "template_type" => {
7977                        selected.child_by_field_name("name").unwrap_or(selected)
7978                    }
7979                    _ => selected,
7980                };
7981                if node_is_within(selected_name, candidate) {
7982                    return true;
7983                }
7984                // A template argument is structurally inside the field subtree,
7985                // but it is an independent reference rather than the selected
7986                // member name.
7987                node = parent;
7988                continue;
7989            }
7990            let receiver = parent
7991                .child_by_field_name("argument")
7992                .or_else(|| parent.child_by_field_name("object"))
7993                .or_else(|| parent.named_child(0));
7994            if !receiver.is_some_and(|receiver| node_is_within(receiver, candidate)) {
7995                // Unknown grammar shape inside a field expression: fail closed
7996                // rather than treating it as a receiver reference.
7997                return true;
7998            }
7999        }
8000        node = parent;
8001    }
8002    false
8003}
8004
8005fn global_field_resolves_to_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
8006    let text = node_text(node, ctx.source);
8007    if !text.contains("::") && ctx.local_shadows.is_shadowed(text) {
8008        return false;
8009    }
8010    if text.contains("::") {
8011        return ctx.visibility.contains_named_symbol(
8012            ctx.file,
8013            text,
8014            TargetKind::GlobalField,
8015            &ctx.spec.target,
8016        );
8017    }
8018    if let Some(namespace) = enclosing_namespace_context(node, ctx.source)
8019        && cpp_namespace_for(&ctx.spec.target).as_deref() == Some(namespace.as_str())
8020    {
8021        return ctx.visibility.contains_named_symbol(
8022            ctx.file,
8023            text,
8024            TargetKind::GlobalField,
8025            &ctx.spec.target,
8026        );
8027    }
8028    if let Some(indexed_scope) = indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, node)
8029        && cpp_namespace_for(&ctx.spec.target).is_some_and(|namespace| {
8030            brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
8031                brokk_bifrost_core::analyzer::Language::Cpp,
8032                &namespace,
8033            ) == indexed_scope
8034        })
8035    {
8036        return ctx.visibility.contains_named_symbol(
8037            ctx.file,
8038            text,
8039            TargetKind::GlobalField,
8040            &ctx.spec.target,
8041        );
8042    }
8043    bare_global_field_uniquely_resolves_to_target(text, ctx)
8044}
8045
8046fn bare_global_field_uniquely_resolves_to_target(text: &str, ctx: &ScanCtx<'_>) -> bool {
8047    let mut matched_target = false;
8048    for unit in ctx.visibility.visible_identifier_candidates(ctx.file, text) {
8049        if !has_persisted_global_field_identity(unit)
8050            || !name_matches_terminal(unit.identifier(), &ctx.spec.member_name)
8051        {
8052            continue;
8053        }
8054        if !name_matches_terminal(cpp_name_for(unit).as_str(), text) {
8055            continue;
8056        }
8057        if same_visible_global_field_symbol(
8058            &ctx.analyzer,
8059            &mut ctx.global_field_internal_linkage_cache.borrow_mut(),
8060            unit,
8061            &ctx.spec.target,
8062        ) {
8063            matched_target = true;
8064        } else {
8065            return false;
8066        }
8067    }
8068    matched_target
8069}
8070
8071pub(crate) fn has_persisted_global_field_identity(unit: &CodeUnit) -> bool {
8072    // C++ type members persist their owner in `short_name` (`Owner.member`), while namespace
8073    // identity lives in `package_name`; global and namespace-scoped fields therefore have a
8074    // terminal-only short name. Keep this hot lookup projection-only instead of asking the
8075    // analyzer for every same-named candidate's parent.
8076    unit.is_field() && !unit.short_name().contains('.')
8077}
8078
8079fn global_field_is_known_non_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
8080    let text = node_text(node, ctx.source);
8081    if !text.contains("::") && ctx.local_shadows.is_shadowed(text) {
8082        return true;
8083    }
8084    if text.contains("::") {
8085        return ctx.visibility.resolve_known_non_target(
8086            ctx.file,
8087            text,
8088            TargetKind::GlobalField,
8089            &ctx.spec.target,
8090        );
8091    }
8092    let Some(namespace) = enclosing_namespace_context(node, ctx.source) else {
8093        return false;
8094    };
8095    cpp_namespace_for(&ctx.spec.target).as_deref() != Some(namespace.as_str())
8096        && ctx
8097            .visibility
8098            .visible_identifier_candidates(ctx.file, &ctx.spec.member_name)
8099            .any(|unit| {
8100                has_persisted_global_field_identity(unit)
8101                    && unit.identifier() == ctx.spec.member_name
8102                    && cpp_namespace_for(unit).as_deref() == Some(namespace.as_str())
8103                    && !same_visible_global_field_symbol(
8104                        &ctx.analyzer,
8105                        &mut ctx.global_field_internal_linkage_cache.borrow_mut(),
8106                        unit,
8107                        &ctx.spec.target,
8108                    )
8109            })
8110}
8111
8112fn maybe_record_member_field_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
8113    if is_c_offsetof_member_node(node) {
8114        maybe_record_c_offsetof_field_hit(node, ctx);
8115        return;
8116    }
8117    if node.kind() == "field_expression" {
8118        let Some(field) = node.child_by_field_name("field") else {
8119            return;
8120        };
8121        if node_text(field, ctx.source) != ctx.spec.member_name {
8122            return;
8123        }
8124        *ctx.raw_match_count += 1;
8125        let receiver = node
8126            .child_by_field_name("argument")
8127            .or_else(|| node.child_by_field_name("object"));
8128        let receiver_resolution =
8129            receiver.map(|receiver| explicit_receiver_target_resolution(receiver, None, ctx));
8130        match receiver_resolution {
8131            Some(MethodReceiverTargetResolution::Target)
8132                if !ctx.analyzer.reference_uses_c_semantics(ctx.file)
8133                    || ctx.visibility.declaration_visible_at_reference(
8134                        &ctx.analyzer,
8135                        ctx.file,
8136                        &ctx.spec.target,
8137                        field,
8138                    ) =>
8139            {
8140                push_hit(field, ctx)
8141            }
8142            Some(MethodReceiverTargetResolution::Target) => {}
8143            Some(MethodReceiverTargetResolution::Missing) | None => push_unproven_hit(field, ctx),
8144            Some(
8145                MethodReceiverTargetResolution::NonTarget
8146                | MethodReceiverTargetResolution::Ambiguous,
8147            ) => {}
8148        }
8149        return;
8150    }
8151
8152    if matches!(node.kind(), "identifier" | "field_identifier")
8153        && name_matches_terminal(node_text(node, ctx.source), &ctx.spec.member_name)
8154        && let Some(designator_owner) =
8155            designated_initializer_owner(&ctx.analyzer, ctx.visibility, ctx.file, ctx.source, node)
8156    {
8157        *ctx.raw_match_count += 1;
8158        match designator_owner {
8159            DesignatedInitializerOwner::Resolved(owner)
8160                if ctx
8161                    .spec
8162                    .owner
8163                    .as_ref()
8164                    .is_some_and(|target_owner| same_visible_symbol(&owner, target_owner)) =>
8165            {
8166                push_hit(node, ctx);
8167            }
8168            DesignatedInitializerOwner::Unresolved => push_unproven_hit(node, ctx),
8169            DesignatedInitializerOwner::Resolved(_) => {}
8170        }
8171        return;
8172    }
8173
8174    let qualified_member_name_matches =
8175        matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
8176            && cpp_name_component_nodes(node)
8177                .and_then(|components| components.last().copied())
8178                .is_some_and(|terminal| node_text(terminal, ctx.source) == ctx.spec.member_name);
8179    if !matches!(
8180        node.kind(),
8181        "identifier"
8182            | "field_identifier"
8183            | "qualified_identifier"
8184            | "scoped_identifier"
8185            | "type_identifier"
8186    ) || (!name_matches_terminal(node_text(node, ctx.source), &ctx.spec.member_name)
8187        && !qualified_member_name_matches)
8188        || !scan_leaf_is_value_position(node, ctx)
8189        || is_declaration_name(node)
8190        || is_member_field_own_declarator(node, ctx)
8191        || is_selected_field_expression_member_descendant(node)
8192        || is_nested_in_qualified_identifier(node)
8193    {
8194        return;
8195    }
8196    *ctx.raw_match_count += 1;
8197    if is_structurally_qualified(node) {
8198        match qualified_owner_resolution(node, ctx) {
8199            QualifiedOwnerResolution::Target => push_hit(node, ctx),
8200            QualifiedOwnerResolution::NonTarget => {}
8201            QualifiedOwnerResolution::Unresolved => push_unproven_hit(node, ctx),
8202        }
8203        return;
8204    }
8205    let text = node_text(node, ctx.source);
8206    if ctx.local_shadows.is_shadowed(text) {
8207        return;
8208    }
8209    let unscoped_enum_match = ctx.spec.enum_owner_kind == EnumOwnerKind::Unscoped
8210        && ctx.visibility.is_visible(ctx.file, &ctx.spec.target);
8211    let owner_context = structured_owner_context_resolution(node, ctx);
8212    if matches!(
8213        owner_context,
8214        StructuredOwnerContextResolution::SelfTarget
8215            | StructuredOwnerContextResolution::InheritedTarget
8216    ) || unscoped_enum_match
8217    {
8218        push_hit(node, ctx);
8219    } else if let Some(target_owner) = (ctx.spec.enum_owner_kind == EnumOwnerKind::Scoped)
8220        .then_some(ctx.spec.owner.as_ref())
8221        .flatten()
8222    {
8223        let resolution =
8224            match resolve_active_using_enum_member(node, ctx) {
8225                ActiveUsingEnumMemberResolution::Block(resolution) => resolution,
8226                ActiveUsingEnumMemberResolution::Class(resolution) => {
8227                    if direct_class_member_shadows(node, ctx) {
8228                        return;
8229                    }
8230                    resolution
8231                }
8232                ActiveUsingEnumMemberResolution::Namespace(resolution) => {
8233                    if let Some(owner) = structured_enclosing_owner(node, ctx) {
8234                        if direct_class_member_shadows(node, ctx) {
8235                            return;
8236                        }
8237                        let complete_same_file_leaf =
8238                            owner.source() == ctx.file
8239                                && ctx.analyzer.type_hierarchy_provider().is_some_and(
8240                                    |hierarchy| hierarchy.get_direct_ancestors(&owner).is_empty(),
8241                                );
8242                        if !complete_same_file_leaf {
8243                            push_unproven_hit(node, ctx);
8244                            return;
8245                        }
8246                    }
8247                    match owner_context {
8248                        StructuredOwnerContextResolution::SelfTarget
8249                        | StructuredOwnerContextResolution::InheritedTarget
8250                        | StructuredOwnerContextResolution::NonTarget => return,
8251                        StructuredOwnerContextResolution::Ambiguous => {
8252                            push_unproven_hit(node, ctx);
8253                            return;
8254                        }
8255                        StructuredOwnerContextResolution::Missing => {}
8256                    }
8257                    if namespace_value_shadows(node, ctx) {
8258                        return;
8259                    }
8260                    resolution
8261                }
8262                ActiveUsingEnumMemberResolution::Missing => {
8263                    if direct_class_member_shadows(node, ctx)
8264                        || (structured_enclosing_owner(node, ctx).is_none()
8265                            && namespace_value_shadows(node, ctx))
8266                    {
8267                        return;
8268                    }
8269                    UsingEnumMemberResolution::Missing
8270                }
8271            };
8272        match resolution {
8273            UsingEnumMemberResolution::Resolved { owner, member }
8274                if same_visible_symbol(&owner, target_owner)
8275                    && same_visible_symbol(&member, &ctx.spec.target) =>
8276            {
8277                push_hit(node, ctx);
8278            }
8279            UsingEnumMemberResolution::Resolved { .. } => {}
8280            UsingEnumMemberResolution::Ambiguous | UsingEnumMemberResolution::Missing => {
8281                push_unproven_hit(node, ctx)
8282            }
8283        }
8284    } else if !matches!(owner_context, StructuredOwnerContextResolution::NonTarget) {
8285        push_unproven_hit(node, ctx);
8286    }
8287}
8288
8289fn maybe_record_c_offsetof_field_hit(node: Node<'_>, ctx: &mut ScanCtx<'_>) {
8290    if node_text(node, ctx.source) != ctx.spec.member_name {
8291        return;
8292    }
8293    *ctx.raw_match_count += 1;
8294    let Some((type_reference, member)) = c_offsetof_member_parts(node) else {
8295        push_unproven_hit(node, ctx);
8296        return;
8297    };
8298    let owner = match resolve_type_node_lexically(
8299        type_reference,
8300        &ctx.analyzer,
8301        ctx.visibility,
8302        &ctx.ordinary_type_imports,
8303        ctx.file,
8304        ctx.source,
8305    ) {
8306        LexicalTypeResolution::Resolved { unit, .. } if unit.is_class() => unit,
8307        LexicalTypeResolution::Resolved { .. }
8308        | LexicalTypeResolution::Ambiguous
8309        | LexicalTypeResolution::Missing => {
8310            push_unproven_hit(member, ctx);
8311            return;
8312        }
8313    };
8314    let candidates = ctx
8315        .visibility
8316        .visible_members_for_owner_name(ctx.file, &owner, ctx.spec.member_name.as_str())
8317        .into_iter()
8318        .filter(|candidate| candidate.is_field())
8319        .collect::<Vec<_>>();
8320    if candidates.len() == 1 && ctx.target_group.contains(candidates[0]) {
8321        push_hit(member, ctx);
8322    } else if candidates.len() > 1 {
8323        push_unproven_hit(member, ctx);
8324    }
8325}
8326
8327enum ActiveUsingEnumMemberResolution {
8328    Block(UsingEnumMemberResolution),
8329    Class(UsingEnumMemberResolution),
8330    Namespace(UsingEnumMemberResolution),
8331    Missing,
8332}
8333
8334fn direct_class_member_shadows(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
8335    structured_enclosing_owner(node, ctx).is_some_and(|owner| {
8336        ctx.visibility
8337            .visible_members_for_owner_name(ctx.file, &owner, &ctx.spec.member_name)
8338            .into_iter()
8339            .next()
8340            .is_some()
8341    })
8342}
8343
8344fn resolve_active_using_enum_member(
8345    node: Node<'_>,
8346    ctx: &ScanCtx<'_>,
8347) -> ActiveUsingEnumMemberResolution {
8348    let block =
8349        ctx.using_enum_owners
8350            .resolve_member(ctx.visibility, ctx.file, &ctx.spec.member_name);
8351    if !matches!(block, UsingEnumMemberResolution::Missing) {
8352        return ActiveUsingEnumMemberResolution::Block(block);
8353    }
8354    let class = structured_enclosing_owner(node, ctx);
8355    let namespace = enclosing_namespace_components(node, ctx.source);
8356    match ctx.semantic_using_enum_owners.resolve_member(
8357        ctx.visibility,
8358        ctx.file,
8359        class.as_ref(),
8360        &namespace,
8361        node.start_byte(),
8362        &ctx.spec.member_name,
8363    ) {
8364        SemanticUsingEnumMemberResolution::Class(resolution) => {
8365            ActiveUsingEnumMemberResolution::Class(resolution)
8366        }
8367        SemanticUsingEnumMemberResolution::Namespace(resolution) => {
8368            ActiveUsingEnumMemberResolution::Namespace(resolution)
8369        }
8370        SemanticUsingEnumMemberResolution::Missing => ActiveUsingEnumMemberResolution::Missing,
8371    }
8372}
8373
8374fn namespace_value_shadows(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
8375    let namespace = enclosing_namespace_components(node, ctx.source).join("::");
8376    !matches!(
8377        resolve_namespace_value(
8378            &ctx.analyzer,
8379            ctx.visibility,
8380            ctx.file,
8381            &namespace,
8382            &ctx.spec.member_name,
8383            node.start_byte(),
8384        ),
8385        NamespaceValueResolution::Missing
8386    )
8387}
8388
8389/// Whether `node` is a component of an enclosing qualified identifier's own
8390/// `scope`/`name` path, so the outer `qualified_identifier` is the single
8391/// reference surfaced for it.
8392///
8393/// A qualified identifier owns only that path. Everything else beneath it is an
8394/// independent reference that its own target scanner must resolve:
8395///
8396/// - `Owner::Template<argument>` holds each template argument outside the path.
8397/// - Error recovery can hang a complete member initializer off an `ERROR` child
8398///   of a synthetic qualified identifier, where no structured path exists.
8399/// - The grammar accepts a `pointer_type_declarator` as a qualified
8400///   identifier's `name`, so `EXPORT_MACRO Result *fn(unsigned int len = kMax);`
8401///   folds a whole parameter list under one `qualified_identifier`. Parameter
8402///   default values there are ordinary value expressions (#2548).
8403///
8404/// Follow the structured `scope`/`name` links rather than every ancestor, which
8405/// covers all three cases with one rule.
8406fn is_nested_in_qualified_identifier(node: Node<'_>) -> bool {
8407    if node.kind() == "qualified_identifier" {
8408        return false;
8409    }
8410    let mut current = node;
8411    while let Some(parent) = current.parent() {
8412        let on_name_path = ["scope", "name"].into_iter().any(|field| {
8413            parent
8414                .child_by_field_name(field)
8415                .is_some_and(|component| same_node(component, current))
8416        });
8417        if !on_name_path {
8418            return false;
8419        }
8420        if parent.kind() == "qualified_identifier" {
8421            return true;
8422        }
8423        current = parent;
8424    }
8425    false
8426}
8427
8428fn receiver_type_units(node: Node<'_>, source: &str, ctx: &ScanCtx<'_>) -> Vec<CodeUnit> {
8429    receiver_type_units_with_budget(node, source, ctx, MAX_RECEIVER_CALL_RESOLUTION_DEPTH)
8430}
8431
8432/// What a receiver spelled as a qualified name denotes.
8433///
8434/// `ns::value.run()` reads the member off the declared type of the variable
8435/// `ns::value`; a type path spelled as a receiver reads it off the type itself.
8436/// Forward navigation and the inverse walk both ask this before typing such a
8437/// receiver, so the two directions accept the same receiver spellings (#2547).
8438pub enum QualifiedReceiverBase {
8439    /// Every visible declaration of the one variable the path names.
8440    Variable(Vec<CodeUnit>),
8441    /// The type the path names when it names no variable.
8442    Type(Option<CodeUnit>),
8443    /// The path names more than one variable; typing either would be a guess.
8444    Ambiguous,
8445}
8446
8447pub fn qualified_receiver_base(
8448    visibility: &VisibilityIndex<'_>,
8449    file: &ProjectFile,
8450    receiver: Node<'_>,
8451    source: &str,
8452) -> QualifiedReceiverBase {
8453    let reference = node_text(receiver, source);
8454    let fields = visibility
8455        .named_candidates(file, reference, TargetKind::GlobalField)
8456        .into_iter()
8457        .filter(has_persisted_global_field_identity)
8458        .collect::<Vec<_>>();
8459    let Some(first) = fields.first() else {
8460        return QualifiedReceiverBase::Type(visibility.resolve_type(file, reference));
8461    };
8462    if fields
8463        .iter()
8464        .skip(1)
8465        .any(|field| !same_visible_symbol(first, field))
8466    {
8467        return QualifiedReceiverBase::Ambiguous;
8468    }
8469    QualifiedReceiverBase::Variable(fields)
8470}
8471
8472fn receiver_type_units_with_budget(
8473    node: Node<'_>,
8474    source: &str,
8475    ctx: &ScanCtx<'_>,
8476    remaining_call_depth: usize,
8477) -> Vec<CodeUnit> {
8478    let mut current = node;
8479    let mut member_chain = Vec::new();
8480    let mut base_units = loop {
8481        match current.kind() {
8482            "field_expression" => {
8483                let Some(member) = current.child_by_field_name("field") else {
8484                    return Vec::new();
8485                };
8486                let Some(receiver) = current
8487                    .child_by_field_name("argument")
8488                    .or_else(|| current.child_by_field_name("object"))
8489                    .or_else(|| current.named_child(0))
8490                else {
8491                    return Vec::new();
8492                };
8493                member_chain.push(node_text(member, source));
8494                current = receiver;
8495            }
8496            "pointer_expression" | "parenthesized_expression" | "subscript_expression" => {
8497                let Some(inner) = current
8498                    .child_by_field_name("argument")
8499                    .or_else(|| current.named_child(0))
8500                else {
8501                    return Vec::new();
8502                };
8503                current = inner;
8504            }
8505            // Tree-sitter uses `field_identifier` for an unqualified member
8506            // field when it appears as the base of another field expression
8507            // (`data_.as_chars()` / `prefix.edge`).  Resolve it through the
8508            // same structured binding and enclosing-owner paths as an
8509            // ordinary identifier; falling through to `resolve_type` would
8510            // treat the field name as a type and lose the receiver identity.
8511            "identifier" | "field_identifier" => {
8512                let name = node_text(current, source);
8513                // Function-like macro locals are visible in the replacement
8514                // range after substitution and shadow caller bindings. The
8515                // receiver scan has no root field, so recover the source tree
8516                // root before asking the visibility index for that binding.
8517                let mut root = current;
8518                while let Some(parent) = ctx.ancestry.parent(root) {
8519                    root = parent;
8520                }
8521                if let Some(binding) = ctx.visibility.macro_local_binding_at(
8522                    ctx.file,
8523                    root,
8524                    source,
8525                    current.start_byte(),
8526                    current.end_byte(),
8527                ) && binding.name == name
8528                {
8529                    let normalized = normalize_cpp_type_name(&binding.type_name);
8530                    let unit = binding
8531                        .proven_unit
8532                        .clone()
8533                        .or_else(|| {
8534                            binding.type_node.and_then(|type_node| {
8535                                resolve_receiver_type_node(type_node, ctx).ok().flatten()
8536                            })
8537                        })
8538                        .or_else(|| receiver_type_name_unit(current, &normalized, ctx));
8539                    // Keep the macro declaration's shadowing boundary even
8540                    // when its type is unavailable: an unresolved macro local
8541                    // cannot be reinterpreted as a static type or outer value.
8542                    break unit.into_iter().collect();
8543                }
8544                let local = ctx.bindings.resolve_symbol(name);
8545                if let Some(bindings) = local.as_precise() {
8546                    break receiver_units_from_bindings(current, bindings, ctx);
8547                }
8548                if ctx.bindings.is_shadowed(name) {
8549                    return Vec::new();
8550                }
8551                let owner = structured_enclosing_owner(current, ctx)
8552                    .filter(CodeUnit::is_class)
8553                    .or_else(|| {
8554                        enclosing_context(current, ctx)
8555                            .owner
8556                            .filter(CodeUnit::is_class)
8557                    });
8558                if let Some(owner) = owner {
8559                    // The enclosing class is only the search root: an implicit
8560                    // member-field receiver can be declared on any base, so the
8561                    // declaring owner comes from the same hierarchy walk the
8562                    // member chain below uses, not from an exact-parent match.
8563                    let declaring_owner = match resolve_declaring_member_owner(
8564                        &ctx.analyzer,
8565                        ctx.visibility,
8566                        ctx.file,
8567                        &owner,
8568                        name,
8569                    ) {
8570                        EnclosingMemberOwnerResolution::Owner(owner) => Some(owner),
8571                        EnclosingMemberOwnerResolution::Missing => None,
8572                        EnclosingMemberOwnerResolution::Ambiguous => return Vec::new(),
8573                    };
8574                    if let Some(declaring_owner) = declaring_owner {
8575                        let implicit_fields = ctx
8576                            .visibility
8577                            .visible_members_for_owner_name(ctx.file, &declaring_owner, name)
8578                            .into_iter()
8579                            .filter(|unit| unit.is_field())
8580                            .collect::<Vec<_>>();
8581                        if !implicit_fields.is_empty() {
8582                            break receiver_units_from_declared_fields(
8583                                implicit_fields,
8584                                current,
8585                                ctx,
8586                            );
8587                        }
8588                    }
8589                }
8590                let global_fields = ctx
8591                    .visibility
8592                    .visible_identifier_candidates(ctx.file, name)
8593                    .filter(|unit| {
8594                        has_persisted_global_field_identity(unit) && unit.identifier() == name
8595                    })
8596                    .collect::<Vec<_>>();
8597                if global_fields.is_empty() {
8598                    break ctx
8599                        .visibility
8600                        .resolve_type(ctx.file, name)
8601                        .into_iter()
8602                        .collect();
8603                }
8604                if let Some(first) = global_fields.first()
8605                    && global_fields.iter().skip(1).any(|field| {
8606                        !same_visible_global_field_symbol(
8607                            &ctx.analyzer,
8608                            &mut ctx.global_field_internal_linkage_cache.borrow_mut(),
8609                            first,
8610                            field,
8611                        )
8612                    })
8613                {
8614                    return Vec::new();
8615                }
8616                break receiver_units_from_declared_fields(global_fields, current, ctx);
8617            }
8618            "call_expression" | "new_expression" => {
8619                break infer_type_from_value_with_budget(current, ctx, remaining_call_depth)
8620                    .and_then(|binding| binding.unit)
8621                    .into_iter()
8622                    .collect();
8623            }
8624            // `((T*)p)->member` is typed by what the cast spells, not by the
8625            // operand it converts (#2981). Pointer depth does not change which
8626            // type declares the member, so only the descriptor's type matters.
8627            "cast_expression" => {
8628                let Some(descriptor) = current.child_by_field_name("type") else {
8629                    return Vec::new();
8630                };
8631                let Ok(unit) = resolve_receiver_type_node(descriptor, ctx) else {
8632                    return Vec::new();
8633                };
8634                break unit.into_iter().collect();
8635            }
8636            "this" if ctx.analyzer.reference_uses_c_semantics(ctx.file) => {
8637                let name = node_text(current, source);
8638                let local = ctx.bindings.resolve_symbol(name);
8639                if let Some(bindings) = local.as_precise() {
8640                    break receiver_units_from_bindings(current, bindings, ctx);
8641                }
8642                return Vec::new();
8643            }
8644            "this" => break enclosing_context(current, ctx).owner.into_iter().collect(),
8645            "qualified_identifier" | "scoped_identifier" => {
8646                match qualified_receiver_base(ctx.visibility, ctx.file, current, source) {
8647                    QualifiedReceiverBase::Variable(fields) => {
8648                        break receiver_units_from_declared_fields(
8649                            fields.iter().collect(),
8650                            current,
8651                            ctx,
8652                        );
8653                    }
8654                    QualifiedReceiverBase::Type(unit) => break unit.into_iter().collect(),
8655                    QualifiedReceiverBase::Ambiguous => return Vec::new(),
8656                }
8657            }
8658            _ => {
8659                break ctx
8660                    .visibility
8661                    .resolve_type(ctx.file, node_text(current, source))
8662                    .into_iter()
8663                    .collect();
8664            }
8665        }
8666    };
8667
8668    base_units = canonical_receiver_units(base_units, ctx);
8669    if base_units.is_empty() {
8670        return Vec::new();
8671    }
8672
8673    while let Some(member_name) = member_chain.pop() {
8674        let mut next_units = Vec::new();
8675        for owner in &base_units {
8676            let declaring_owner = match resolve_declaring_member_owner(
8677                &ctx.analyzer,
8678                ctx.visibility,
8679                ctx.file,
8680                owner,
8681                member_name,
8682            ) {
8683                EnclosingMemberOwnerResolution::Owner(owner) => owner,
8684                EnclosingMemberOwnerResolution::Missing => continue,
8685                EnclosingMemberOwnerResolution::Ambiguous => return Vec::new(),
8686            };
8687            let fields = ctx.visibility.visible_members_for_owner_name(
8688                ctx.file,
8689                &declaring_owner,
8690                member_name,
8691            );
8692            for field in fields.into_iter().filter(|unit| unit.is_field()) {
8693                let Some(unit) =
8694                    field_declared_binding(&ctx.analyzer, ctx.visibility, ctx.file, field)
8695                        .and_then(|binding| binding.unit)
8696                        .or_else(|| recovered_receiver_field_type(current, field, ctx))
8697                else {
8698                    continue;
8699                };
8700                if !next_units
8701                    .iter()
8702                    .any(|existing| same_visible_symbol(existing, &unit))
8703                {
8704                    next_units.push(unit);
8705                }
8706            }
8707        }
8708        if next_units.is_empty() {
8709            return Vec::new();
8710        }
8711        base_units = unanimous_receiver_units(next_units);
8712        if base_units.is_empty() {
8713            return Vec::new();
8714        }
8715    }
8716    base_units
8717}
8718
8719fn receiver_units_from_bindings(
8720    node: Node<'_>,
8721    bindings: &HashSet<CppScanBinding>,
8722    ctx: &ScanCtx<'_>,
8723) -> Vec<CodeUnit> {
8724    let mut units = Vec::new();
8725    for binding in bindings {
8726        let raw_unit = if let Some(unit) = &binding.unit {
8727            unit.clone()
8728        } else {
8729            let Some(type_name) = binding.type_name.as_deref() else {
8730                return Vec::new();
8731            };
8732            let Some(unit) = receiver_type_name_unit(node, type_name, ctx) else {
8733                return Vec::new();
8734            };
8735            unit
8736        };
8737        if let Some(unit) = canonical_receiver_unit(&raw_unit, ctx) {
8738            // Type aliases are represented as class units. When an alias has
8739            // a dependent target, canonicalization deliberately preserves
8740            // that alias rather than inventing a concrete class. Give the
8741            // existing target-guided structured recovery a chance to prove
8742            // the queried owner before accepting that unresolved identity.
8743            if same_visible_symbol(&unit, &raw_unit)
8744                && let Some(recovered) = recovered_receiver_alias_target(node, &raw_unit, ctx)
8745            {
8746                units.push(recovered);
8747                continue;
8748            }
8749            units.push(unit);
8750            continue;
8751        }
8752        if let Some(unit) = recovered_receiver_alias_target(node, &raw_unit, ctx) {
8753            units.push(unit);
8754            continue;
8755        }
8756        return Vec::new();
8757    }
8758    unanimous_receiver_units(units)
8759}
8760
8761/// Resolve a using-alias receiver from its declaration's structured RHS when
8762/// the alias target index cannot cross a malformed namespace-sentinel node.
8763/// The inverse target owner supplies only the exact class identity to prove;
8764/// lexical AST resolution still decides whether the alias denotes that class.
8765fn recovered_receiver_alias_target(
8766    reference: Node<'_>,
8767    alias: &CodeUnit,
8768    ctx: &ScanCtx<'_>,
8769) -> Option<CodeUnit> {
8770    if !ctx
8771        .analyzer
8772        .type_alias_provider()
8773        .is_some_and(|provider| provider.is_type_alias(alias))
8774    {
8775        return None;
8776    }
8777    let target = ctx.spec.owner.as_ref()?.clone();
8778    if !target.is_class() || alias.source() != ctx.file {
8779        return None;
8780    }
8781    let range = ctx
8782        .analyzer
8783        .ranges(alias)
8784        .into_iter()
8785        .find(|range| range.start_byte < range.end_byte)?;
8786    let mut node =
8787        root_node(reference).descendant_for_byte_range(range.start_byte, range.end_byte)?;
8788    while !matches!(node.kind(), "alias_declaration" | "type_definition") {
8789        node = ctx.ancestry.parent(node)?;
8790    }
8791    let type_descriptor = node.child_by_field_name("type")?;
8792    let type_node = receiver_type_node_base(type_descriptor);
8793    let resolution = resolve_type_node_lexically_for_target(
8794        type_node,
8795        &ctx.analyzer,
8796        ctx.visibility,
8797        &ctx.ordinary_type_imports,
8798        ctx.file,
8799        ctx.source,
8800        &target,
8801        Some(&ctx.lexical_scope_cache),
8802        ctx.recovered_sentinel_scope(type_node).as_deref(),
8803    );
8804    if let LexicalTypeResolution::Resolved {
8805        unit, candidates, ..
8806    } = resolution
8807        && (same_visible_symbol(&unit, &target)
8808            || candidates
8809                .iter()
8810                .any(|candidate| same_visible_symbol(candidate, &target)))
8811    {
8812        return Some(target);
8813    }
8814    let (components, global) = type_reference_components(type_node, ctx.source)?;
8815    if !global
8816        && components.len() == 2
8817        && cpp_active_template_type_parameter(type_node, &components[0], ctx.source, &ctx.ancestry)
8818        && dependent_nested_alias_concrete_target(
8819            &ctx.analyzer,
8820            ctx.visibility,
8821            ctx.file,
8822            alias,
8823            &components[1],
8824            type_node,
8825        )
8826        .is_some_and(|unit| same_visible_symbol(&unit, &target))
8827    {
8828        return Some(target);
8829    }
8830    let scope = ctx
8831        .recovered_sentinel_scope(type_node)
8832        .or_else(|| indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, type_node))?;
8833    let path_matches = indexed_scope_matches_target_name(&scope, &components, global, &target);
8834    let visible = ctx.visibility.external_type_candidate_visible_in_context(
8835        &ctx.analyzer,
8836        ctx.file,
8837        &target,
8838        type_node,
8839    );
8840    (path_matches && visible).then_some(target)
8841}
8842
8843/// The one concrete class that `alias`, spelled `Param::nested_name` through an
8844/// active template type parameter `Param`, can name: every other visible
8845/// class-owned alias named `nested_name` must reach the same indexed class
8846/// (#2250). `type_node` is the alias's target type node, whose guard context
8847/// each candidate must be compatible with. Competing concrete targets answer
8848/// `None`.
8849pub fn dependent_nested_alias_concrete_target(
8850    analyzer: &CppGraphSource<'_>,
8851    visibility: &VisibilityIndex<'_>,
8852    file: &ProjectFile,
8853    alias: &CodeUnit,
8854    nested_name: &str,
8855    type_node: Node<'_>,
8856) -> Option<CodeUnit> {
8857    let alias_provider = analyzer.type_alias_provider()?;
8858    let concrete = visibility
8859        .visible_identifier_candidates(file, nested_name)
8860        .filter(|candidate| {
8861            alias_provider.is_type_alias(candidate)
8862                && !same_visible_symbol(candidate, alias)
8863                && type_owner_of(analyzer, candidate).is_some_and(|owner| owner.is_class())
8864                && visibility.is_physically_visible(file, candidate)
8865                && visibility.external_type_candidate_guard_compatible_in_context(
8866                    analyzer, file, candidate, type_node,
8867                )
8868        })
8869        .filter_map(|candidate| {
8870            let canonical =
8871                visibility.canonical_visible_full_type_unit(analyzer, file, candidate)?;
8872            // Another dependent alias can have the same nested name but
8873            // still canonicalize only to itself. It supplies no concrete
8874            // receiver identity and therefore cannot compete with an
8875            // alias that reaches an indexed class.
8876            (!same_visible_symbol(&canonical, candidate)).then_some(canonical)
8877        })
8878        .collect::<Vec<_>>();
8879    match unanimous_receiver_units(concrete).as_slice() {
8880        [unit] => Some(unit.clone()),
8881        _ => None,
8882    }
8883}
8884
8885fn receiver_type_name_unit(node: Node<'_>, type_name: &str, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
8886    let normalized = normalize_cpp_type_name(type_name);
8887    if normalized.is_empty() {
8888        return None;
8889    }
8890
8891    // A function-local alias is intentionally absent from the visibility
8892    // index. Recover its RHS from the structured alias declaration before
8893    // trying file-visible type lookup; this keeps the alias's lexical shadow
8894    // boundary intact.
8895    if let Some(alias_type) = local_receiver_alias_type_node(node, &normalized, ctx) {
8896        match resolve_receiver_type_node(alias_type, ctx) {
8897            Ok(Some(unit)) => return Some(unit),
8898            Err(_) => return None,
8899            Ok(None) => {}
8900        }
8901    }
8902
8903    match resolve_receiver_type_name_lexically(node, &normalized, ctx) {
8904        LexicalTypeResolution::Resolved { unit, .. } => return Some(unit),
8905        LexicalTypeResolution::Ambiguous => return None,
8906        LexicalTypeResolution::Missing => {}
8907    }
8908    let candidates = ctx
8909        .visibility
8910        .type_name_candidates(ctx.file, &normalized)
8911        .into_iter()
8912        .filter_map(|candidate| canonical_receiver_unit(candidate, ctx))
8913        .collect();
8914    unanimous_receiver_units(candidates).into_iter().next()
8915}
8916
8917/// The receiver type a type node names: the visible indexed type it resolves
8918/// to, else the type its components name in the enclosing lexical scope.
8919///
8920/// A `type_descriptor` (a cast's type, an alias declaration's right-hand side)
8921/// is unwrapped to its type specifier first, so every caller that has a spelled
8922/// type reads it the same way. `Err` reports a template whose arguments could
8923/// not be resolved; that is a structured failure, not an absent type.
8924fn resolve_receiver_type_node(
8925    type_node: Node<'_>,
8926    ctx: &ScanCtx<'_>,
8927) -> std::result::Result<Option<CodeUnit>, CppTemplateResolutionError> {
8928    let type_node = receiver_type_node_base(type_node);
8929    if let Some(unit) = ctx
8930        .visibility
8931        .resolve_type_node_result(ctx.file, type_node, ctx.source)?
8932    {
8933        return Ok(Some(unit));
8934    }
8935    Ok(resolve_receiver_type_node_lexically(type_node, ctx))
8936}
8937
8938fn resolve_receiver_type_node_lexically(
8939    type_node: Node<'_>,
8940    ctx: &ScanCtx<'_>,
8941) -> Option<CodeUnit> {
8942    let type_node = receiver_type_node_base(type_node);
8943    let components = cpp_type_name_components(type_node, ctx.source)?;
8944    let lexical_scope = match enclosing_lexical_scope_components(
8945        type_node,
8946        &ctx.analyzer,
8947        ctx.visibility,
8948        ctx.file,
8949        ctx.source,
8950    ) {
8951        LexicalScopeResolution::Resolved(scope) => scope,
8952        LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => return None,
8953    };
8954    match ctx.visibility.resolve_type_components_lexically(
8955        &ctx.analyzer,
8956        ctx.file,
8957        &components,
8958        is_globally_qualified_cpp_name(type_node),
8959        &lexical_scope,
8960    ) {
8961        LexicalTypeResolution::Resolved { unit, .. } => Some(unit),
8962        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
8963    }
8964}
8965
8966fn receiver_type_node_base(mut node: Node<'_>) -> Node<'_> {
8967    while matches!(node.kind(), "type_descriptor" | "dependent_type") {
8968        let Some(inner) = node.child_by_field_name("type").or_else(|| {
8969            if node.kind() == "dependent_type" {
8970                node.named_child(0)
8971            } else {
8972                None
8973            }
8974        }) else {
8975            break;
8976        };
8977        node = inner;
8978    }
8979    node
8980}
8981
8982fn resolve_receiver_type_name_lexically(
8983    node: Node<'_>,
8984    normalized: &str,
8985    ctx: &ScanCtx<'_>,
8986) -> LexicalTypeResolution {
8987    let components = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
8988        brokk_bifrost_core::analyzer::Language::Cpp,
8989        normalized,
8990    );
8991    if components.is_empty() {
8992        return LexicalTypeResolution::Missing;
8993    }
8994    let lexical_scope = match enclosing_lexical_scope_components(
8995        node,
8996        &ctx.analyzer,
8997        ctx.visibility,
8998        ctx.file,
8999        ctx.source,
9000    ) {
9001        LexicalScopeResolution::Resolved(scope) => scope,
9002        LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
9003        LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
9004    };
9005    ctx.visibility.resolve_type_components_lexically(
9006        &ctx.analyzer,
9007        ctx.file,
9008        &components,
9009        normalized.starts_with("::"),
9010        &lexical_scope,
9011    )
9012}
9013
9014fn local_receiver_alias_type_node<'tree>(
9015    node: Node<'tree>,
9016    name: &str,
9017    ctx: &ScanCtx<'_>,
9018) -> Option<Node<'tree>> {
9019    let callable = nearest_callable_scope(node)?;
9020    let mut root_callable = callable;
9021    // See `target_guided_nested_type_terminal_hit`: the result carries the
9022    // caller's tree lifetime.
9023    let mut ancestor = callable.parent();
9024    while let Some(current) = ancestor {
9025        if matches!(current.kind(), "function_definition" | "lambda_expression") {
9026            root_callable = current;
9027        }
9028        ancestor = current.parent();
9029    }
9030
9031    let mut stack = vec![root_callable];
9032    let mut best = None;
9033    while let Some(current) = stack.pop() {
9034        if current.start_byte() >= node.start_byte() {
9035            continue;
9036        }
9037        if local_type_alias_name_node(current)
9038            .is_some_and(|alias_name| node_text(alias_name, ctx.source) == name)
9039            && local_alias_scope_contains_node(current, node)
9040        {
9041            let replace = best
9042                .is_none_or(|existing: Node<'tree>| existing.start_byte() < current.start_byte());
9043            if replace {
9044                best = current.child_by_field_name("type");
9045            }
9046        }
9047        let mut cursor = current.walk();
9048        stack.extend(current.named_children(&mut cursor));
9049    }
9050    best
9051}
9052
9053fn canonical_receiver_units(units: Vec<CodeUnit>, ctx: &ScanCtx<'_>) -> Vec<CodeUnit> {
9054    let mut canonical = Vec::with_capacity(units.len());
9055    for unit in units {
9056        let Some(unit) = canonical_receiver_unit(&unit, ctx) else {
9057            return Vec::new();
9058        };
9059        canonical.push(unit);
9060    }
9061    unanimous_receiver_units(canonical)
9062}
9063
9064fn canonical_receiver_unit(unit: &CodeUnit, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
9065    if let Some(cached) = ctx.receiver_canonical_type_cache.borrow().get(unit) {
9066        return cached.clone();
9067    }
9068    let canonical = ctx
9069        .visibility
9070        .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, unit);
9071    ctx.receiver_canonical_type_cache
9072        .borrow_mut()
9073        .insert(unit.clone(), canonical.clone());
9074    canonical
9075}
9076
9077fn receiver_units_from_declared_fields(
9078    fields: Vec<&CodeUnit>,
9079    reference: Node<'_>,
9080    ctx: &ScanCtx<'_>,
9081) -> Vec<CodeUnit> {
9082    let Some(first) = fields.first() else {
9083        return Vec::new();
9084    };
9085    if fields
9086        .iter()
9087        .skip(1)
9088        .any(|field| !same_visible_symbol(first, field))
9089    {
9090        return Vec::new();
9091    }
9092    unanimous_receiver_units(
9093        fields
9094            .into_iter()
9095            .filter_map(|field| {
9096                field_declared_binding(&ctx.analyzer, ctx.visibility, ctx.file, field)
9097                    .and_then(|binding| binding.unit)
9098                    .or_else(|| recovered_receiver_field_type(reference, field, ctx))
9099            })
9100            .collect(),
9101    )
9102}
9103
9104/// Resolve a field receiver's declared type from its structured declaration
9105/// when the persisted type fact was built under a malformed sentinel scope.
9106/// The queried member owner supplies the exact class identity to prove; the
9107/// declaration's type node and recovered lexical path provide the evidence.
9108fn recovered_receiver_field_type(
9109    reference: Node<'_>,
9110    field: &CodeUnit,
9111    ctx: &ScanCtx<'_>,
9112) -> Option<CodeUnit> {
9113    let target = ctx.spec.owner.as_ref()?.clone();
9114    if !target.is_class() || field.source() != ctx.file {
9115        return None;
9116    }
9117    let range = ctx
9118        .analyzer
9119        .ranges(field)
9120        .into_iter()
9121        .find(|range| range.start_byte < range.end_byte)?;
9122    let mut declaration =
9123        root_node(reference).descendant_for_byte_range(range.start_byte, range.end_byte)?;
9124    while !matches!(declaration.kind(), "declaration" | "field_declaration") {
9125        declaration = ctx.ancestry.parent(declaration)?;
9126    }
9127    let type_node = first_type_child(declaration)?;
9128    let resolution = resolve_type_node_lexically_for_target(
9129        type_node,
9130        &ctx.analyzer,
9131        ctx.visibility,
9132        &ctx.ordinary_type_imports,
9133        ctx.file,
9134        ctx.source,
9135        &target,
9136        Some(&ctx.lexical_scope_cache),
9137        ctx.recovered_sentinel_scope(type_node).as_deref(),
9138    );
9139    if let LexicalTypeResolution::Resolved {
9140        unit, candidates, ..
9141    } = resolution
9142        && (same_visible_symbol(&unit, &target)
9143            || candidates
9144                .iter()
9145                .any(|candidate| same_visible_symbol(candidate, &target)))
9146    {
9147        return Some(target);
9148    }
9149    let type_node = receiver_type_node_base(type_node);
9150    let (components, global) = type_reference_components(type_node, ctx.source)?;
9151    let scope = ctx
9152        .recovered_sentinel_scope(type_node)
9153        .or_else(|| indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, type_node))?;
9154    (indexed_scope_matches_target_name(&scope, &components, global, &target)
9155        && ctx.visibility.external_type_candidate_visible_in_context(
9156            &ctx.analyzer,
9157            ctx.file,
9158            &target,
9159            type_node,
9160        ))
9161    .then_some(target)
9162}
9163
9164fn unanimous_receiver_units(units: Vec<CodeUnit>) -> Vec<CodeUnit> {
9165    let mut unique = Vec::new();
9166    for unit in units {
9167        if !unique
9168            .iter()
9169            .any(|existing| same_visible_symbol(existing, &unit))
9170        {
9171            unique.push(unit);
9172            if unique.len() > 1 {
9173                return Vec::new();
9174            }
9175        }
9176    }
9177    unique
9178}
9179
9180fn receiver_matches_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9181    let Some(owner) = ctx.spec.owner.as_ref() else {
9182        return false;
9183    };
9184    match node.kind() {
9185        // `declaring_owner_for_explicit_receiver` already tried the complete field chain.
9186        // When that structured lookup fails, the base expression's owner is not the field's
9187        // type: treating `value_` as `Value` would misclassify
9188        // `value_.map_->clear()` as `Value::clear`. Direct `this->clear()` reaches this helper
9189        // with the `this` node itself, so failing closed for an unresolved field chain does not
9190        // discard genuine self calls.
9191        "field_expression" => false,
9192        "call_expression" => node
9193            .child_by_field_name("function")
9194            .is_some_and(|function| receiver_matches_target(function, ctx)),
9195        "pointer_expression" | "parenthesized_expression" | "subscript_expression" => node
9196            .child_by_field_name("argument")
9197            .or_else(|| node.named_child(0))
9198            .is_some_and(|child| receiver_matches_target(child, ctx)),
9199        "identifier" | "this" if ctx.analyzer.reference_uses_c_semantics(ctx.file) => ctx
9200            .bindings
9201            .resolve_symbol(node_text(node, ctx.source))
9202            .as_precise()
9203            .is_some_and(|targets| {
9204                targets
9205                    .iter()
9206                    .filter_map(|target| target.unit.as_ref())
9207                    .any(|target| {
9208                        receiver_owner_matches_target(target, owner, node.start_byte(), ctx)
9209                    })
9210            }),
9211        "this" => same_owner_context(node, ctx),
9212        _ => qualified_owner_matches(node, ctx),
9213    }
9214}
9215
9216fn declaring_owner_for_explicit_receiver(
9217    receiver: Node<'_>,
9218    call_arity: Option<usize>,
9219    ctx: &ScanCtx<'_>,
9220) -> EnclosingMemberOwnerResolution {
9221    if receiver_is_self_like(receiver, ctx.analyzer.reference_uses_c_semantics(ctx.file)) {
9222        return EnclosingMemberOwnerResolution::Missing;
9223    }
9224    declaring_owner_from_receiver_units(
9225        receiver_type_units(receiver, ctx.source, ctx),
9226        receiver.start_byte(),
9227        call_arity,
9228        ctx,
9229    )
9230}
9231
9232/// The owner that declares the queried member for a receiver already typed.
9233///
9234/// `reference_byte` is the reference's position in the scanned file, which
9235/// decides which declarations are visible there. A receiver recovered from a
9236/// macro replacement is typed against the sentinel parse but still reported at
9237/// its bytes in the defining file, so the two arrive separately.
9238fn declaring_owner_from_receiver_units(
9239    receiver_units: Vec<CodeUnit>,
9240    reference_byte: usize,
9241    call_arity: Option<usize>,
9242    ctx: &ScanCtx<'_>,
9243) -> EnclosingMemberOwnerResolution {
9244    let mut declaring_owner = None;
9245    for receiver_owner in receiver_units {
9246        if ctx.spec.owner.as_ref().is_some_and(|target_owner| {
9247            receiver_owner_matches_target(&receiver_owner, target_owner, reference_byte, ctx)
9248        }) {
9249            if declaring_owner
9250                .as_ref()
9251                .is_some_and(|existing| !same_visible_symbol(existing, &receiver_owner))
9252            {
9253                return EnclosingMemberOwnerResolution::Ambiguous;
9254            }
9255            declaring_owner = Some(receiver_owner);
9256            continue;
9257        }
9258        let ordinary = cached_declaring_member_owner(&receiver_owner, ctx);
9259        let owner_resolution = match call_arity {
9260            Some(arity) => resolve_declaring_callable_owner(
9261                &ctx.analyzer,
9262                ctx.visibility,
9263                ctx.file,
9264                ordinary,
9265                &ctx.spec.member_name,
9266                arity,
9267            ),
9268            None => ordinary,
9269        };
9270        match owner_resolution {
9271            EnclosingMemberOwnerResolution::Owner(owner) => {
9272                if declaring_owner
9273                    .as_ref()
9274                    .is_some_and(|existing| !same_visible_symbol(existing, &owner))
9275                {
9276                    return EnclosingMemberOwnerResolution::Ambiguous;
9277                }
9278                declaring_owner = Some(owner);
9279            }
9280            EnclosingMemberOwnerResolution::Ambiguous => {
9281                return EnclosingMemberOwnerResolution::Ambiguous;
9282            }
9283            EnclosingMemberOwnerResolution::Missing => {}
9284        }
9285    }
9286    declaring_owner
9287        .map(EnclosingMemberOwnerResolution::Owner)
9288        .unwrap_or(EnclosingMemberOwnerResolution::Missing)
9289}
9290
9291fn declaring_owner_from_call_function(
9292    function: Node<'_>,
9293    call_arity: Option<usize>,
9294    ctx: &ScanCtx<'_>,
9295) -> Option<EnclosingMemberOwnerResolution> {
9296    match function.kind() {
9297        "field_expression" => function
9298            .child_by_field_name("argument")
9299            .or_else(|| function.child_by_field_name("object"))
9300            .map(|receiver| declaring_owner_for_explicit_receiver(receiver, call_arity, ctx))
9301            .or(Some(EnclosingMemberOwnerResolution::Missing)),
9302        "call_expression" => function
9303            .child_by_field_name("function")
9304            .and_then(|inner| declaring_owner_from_call_function(inner, call_arity, ctx)),
9305        _ => None,
9306    }
9307}
9308
9309enum MethodReceiverTargetResolution {
9310    Target,
9311    NonTarget,
9312    Ambiguous,
9313    Missing,
9314}
9315
9316fn method_receiver_target_resolution(
9317    node: Node<'_>,
9318    declaring_owner: EnclosingMemberOwnerResolution,
9319    ctx: &ScanCtx<'_>,
9320) -> MethodReceiverTargetResolution {
9321    match declaring_owner {
9322        EnclosingMemberOwnerResolution::Owner(_) | EnclosingMemberOwnerResolution::Ambiguous => {
9323            declaring_owner_target_resolution(declaring_owner, node.start_byte(), ctx)
9324        }
9325        EnclosingMemberOwnerResolution::Missing if ctx.spec.owner.is_none() => {
9326            MethodReceiverTargetResolution::Missing
9327        }
9328        EnclosingMemberOwnerResolution::Missing if receiver_matches_target(node, ctx) => {
9329            MethodReceiverTargetResolution::Target
9330        }
9331        EnclosingMemberOwnerResolution::Missing if receiver_has_known_non_target(node, ctx) => {
9332            MethodReceiverTargetResolution::NonTarget
9333        }
9334        EnclosingMemberOwnerResolution::Missing => MethodReceiverTargetResolution::Missing,
9335    }
9336}
9337
9338/// Decide the queried member against a receiver's declaring owner alone.
9339///
9340/// This is the part of receiver typing that needs nothing but the owner and
9341/// the reference's position, so a member call recovered from a macro
9342/// replacement reaches the same verdict as ordinary code even though its
9343/// syntax lives in a separate sentinel parse.
9344fn declaring_owner_target_resolution(
9345    declaring_owner: EnclosingMemberOwnerResolution,
9346    reference_byte: usize,
9347    ctx: &ScanCtx<'_>,
9348) -> MethodReceiverTargetResolution {
9349    let Some(target_owner) = ctx.spec.owner.as_ref() else {
9350        return MethodReceiverTargetResolution::Missing;
9351    };
9352    match declaring_owner {
9353        EnclosingMemberOwnerResolution::Owner(owner)
9354            if receiver_owner_matches_target(&owner, target_owner, reference_byte, ctx) =>
9355        {
9356            MethodReceiverTargetResolution::Target
9357        }
9358        EnclosingMemberOwnerResolution::Owner(owner)
9359            if receiver_owner_is_known_non_target(&owner, target_owner, reference_byte, ctx) =>
9360        {
9361            MethodReceiverTargetResolution::NonTarget
9362        }
9363        EnclosingMemberOwnerResolution::Owner(_) | EnclosingMemberOwnerResolution::Missing => {
9364            MethodReceiverTargetResolution::Missing
9365        }
9366        EnclosingMemberOwnerResolution::Ambiguous => MethodReceiverTargetResolution::Ambiguous,
9367    }
9368}
9369
9370fn explicit_receiver_target_resolution(
9371    receiver: Node<'_>,
9372    call_arity: Option<usize>,
9373    ctx: &ScanCtx<'_>,
9374) -> MethodReceiverTargetResolution {
9375    method_receiver_target_resolution(
9376        receiver,
9377        declaring_owner_for_explicit_receiver(receiver, call_arity, ctx),
9378        ctx,
9379    )
9380}
9381
9382fn call_function_target_resolution(
9383    function: Node<'_>,
9384    ctx: &ScanCtx<'_>,
9385) -> MethodReceiverTargetResolution {
9386    let call_arity = ctx.ancestry.parent(function).and_then(|call| {
9387        (call.kind() == "call_expression")
9388            .then(|| {
9389                ctx.visibility
9390                    .call_arity_evidence(ctx.file, call, ctx.source)
9391                    .exact()
9392            })
9393            .flatten()
9394    });
9395    let Some(declaring_owner) = declaring_owner_from_call_function(function, call_arity, ctx)
9396    else {
9397        // A bare function identifier has an implicit receiver. Do not reinterpret
9398        // that identifier as a same-named type or value before enclosing-owner
9399        // lookup gets a chance to establish the member call.
9400        return MethodReceiverTargetResolution::Missing;
9401    };
9402    method_receiver_target_resolution(function, declaring_owner, ctx)
9403}
9404
9405fn receiver_owner_matches_target(
9406    receiver_owner: &CodeUnit,
9407    target_owner: &CodeUnit,
9408    reference_byte: usize,
9409    ctx: &ScanCtx<'_>,
9410) -> bool {
9411    same_symbol(receiver_owner, target_owner)
9412        || same_logical_symbol(receiver_owner, target_owner)
9413            && (ctx.visibility.is_physically_visible(ctx.file, target_owner)
9414                || (ctx.spec.owner_is_forward_declaration
9415                    && ctx
9416                        .visibility
9417                        .is_physically_visible(ctx.file, receiver_owner))
9418                || visible_target_peer_matches_owner(receiver_owner, reference_byte, ctx)
9419                || target_group_contains_owner_peer(receiver_owner, ctx))
9420}
9421
9422fn receiver_owner_is_known_non_target(
9423    receiver_owner: &CodeUnit,
9424    target_owner: &CodeUnit,
9425    reference_byte: usize,
9426    ctx: &ScanCtx<'_>,
9427) -> bool {
9428    if receiver_owner_matches_target(receiver_owner, target_owner, reference_byte, ctx) {
9429        return false;
9430    }
9431    if !same_logical_symbol(receiver_owner, target_owner) {
9432        return true;
9433    }
9434    !ctx.target_group.iter().any(|target| {
9435        same_logical_symbol(target, &ctx.spec.target) && target.source() == target_owner.source()
9436    })
9437}
9438
9439fn target_group_contains_owner_peer(owner: &CodeUnit, ctx: &ScanCtx<'_>) -> bool {
9440    ctx.visibility
9441        .external_type_declaration_visible_at(ctx.file, owner, usize::MAX)
9442        && ctx.target_group.iter().any(|target| {
9443            type_owner_of(&ctx.analyzer, target)
9444                .as_ref()
9445                .is_some_and(|target_owner| owner_peer_matches(target_owner, owner))
9446        })
9447}
9448
9449fn owner_peer_matches(candidate_owner: &CodeUnit, owner: &CodeUnit) -> bool {
9450    same_symbol(candidate_owner, owner)
9451        || (same_logical_symbol(candidate_owner, owner)
9452            && candidate_owner.source() == owner.source())
9453}
9454
9455fn visible_target_peer_matches_owner(
9456    owner: &CodeUnit,
9457    reference_byte: usize,
9458    ctx: &ScanCtx<'_>,
9459) -> bool {
9460    ctx.visibility
9461        .external_type_declaration_visible_at(ctx.file, owner, reference_byte)
9462        && ctx
9463            .visibility
9464            .visible_identifier_candidates(ctx.file, &ctx.spec.member_name)
9465            .any(|candidate| {
9466                cpp_callable_definitions_share_identity_evidence(
9467                    &ctx.analyzer,
9468                    candidate,
9469                    &ctx.spec.target,
9470                ) && ctx.visibility.declaration_visible_at(
9471                    &ctx.analyzer,
9472                    ctx.file,
9473                    candidate,
9474                    reference_byte,
9475                ) && type_owner_of(&ctx.analyzer, candidate)
9476                    .as_ref()
9477                    .is_some_and(|candidate_owner| owner_peer_matches(candidate_owner, owner))
9478            })
9479}
9480
9481fn call_function_has_direct_self_receiver(function: Node<'_>, reference_is_c: bool) -> bool {
9482    match function.kind() {
9483        "field_expression" => function
9484            .child_by_field_name("argument")
9485            .or_else(|| function.child_by_field_name("object"))
9486            .is_some_and(|receiver| receiver_is_self_like(receiver, reference_is_c)),
9487        _ => receiver_is_self_like(function, reference_is_c),
9488    }
9489}
9490
9491fn receiver_has_known_non_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9492    let Some(owner) = ctx.spec.owner.as_ref() else {
9493        return false;
9494    };
9495    match node.kind() {
9496        "field_expression" => node
9497            .child_by_field_name("argument")
9498            .or_else(|| node.child_by_field_name("object"))
9499            .is_some_and(|receiver| {
9500                // `this` names the enclosing class, not necessarily the class that
9501                // declares the invoked member. Let the hierarchy-aware enclosing-owner
9502                // lookup decide whether this is a same-owner call, an inherited base
9503                // member, a nearer override, or an ambiguous base. Rejecting a derived
9504                // `this` merely because its immediate type differs from the target owner
9505                // drops genuine inherited calls (#2541).
9506                if receiver_is_self_like(
9507                    receiver,
9508                    ctx.analyzer.reference_uses_c_semantics(ctx.file),
9509                ) {
9510                    return false;
9511                }
9512                if receiver_is_known_function_declarator(receiver, ctx) {
9513                    return true;
9514                }
9515                let units = receiver_type_units(receiver, ctx.source, ctx);
9516                !units.is_empty()
9517                    && units.iter().all(|target| {
9518                        receiver_owner_is_known_non_target(target, owner, node.start_byte(), ctx)
9519                    })
9520            }),
9521        "call_expression" => node
9522            .child_by_field_name("function")
9523            .is_some_and(|function| receiver_has_known_non_target(function, ctx)),
9524        "pointer_expression" | "parenthesized_expression" | "subscript_expression" => node
9525            .child_by_field_name("argument")
9526            .or_else(|| node.named_child(0))
9527            .is_some_and(|child| receiver_has_known_non_target(child, ctx)),
9528        "identifier" | "this" if ctx.analyzer.reference_uses_c_semantics(ctx.file) => ctx
9529            .bindings
9530            .resolve_symbol(node_text(node, ctx.source))
9531            .as_precise()
9532            .is_some_and(|targets| {
9533                let units = targets
9534                    .iter()
9535                    .filter_map(|target| target.unit.as_ref())
9536                    .collect::<Vec<_>>();
9537                !units.is_empty()
9538                    && units.iter().all(|target| {
9539                        receiver_owner_is_known_non_target(target, owner, node.start_byte(), ctx)
9540                    })
9541            }),
9542        "this" => known_non_target_owner_context(node, ctx),
9543        "qualified_identifier" | "scoped_identifier" | "field_identifier" => {
9544            qualified_owner_is_known_non_target(node, ctx)
9545        }
9546        _ => false,
9547    }
9548}
9549
9550fn receiver_is_known_function_declarator(receiver: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9551    if receiver.kind() != "identifier" {
9552        return false;
9553    }
9554    let receiver_name = node_text(receiver, ctx.source);
9555    let mut current = receiver;
9556    while let Some(parent) = ctx.ancestry.parent(current) {
9557        if parent.kind() == "compound_statement" {
9558            let mut cursor = parent.walk();
9559            for statement in parent.named_children(&mut cursor) {
9560                if statement.start_byte() >= receiver.start_byte() {
9561                    break;
9562                }
9563                if statement.kind() != "declaration" || statement.end_byte() > receiver.start_byte()
9564                {
9565                    continue;
9566                }
9567                let type_text = statement
9568                    .child_by_field_name("type")
9569                    .or_else(|| first_type_child(statement))
9570                    .map(|type_node| node_text(type_node, ctx.source));
9571                let mut declaration_cursor = statement.walk();
9572                for child in statement.named_children(&mut declaration_cursor) {
9573                    let declarator = if child.kind() == "init_declarator" {
9574                        child.child_by_field_name("declarator")
9575                    } else if is_declarator_node(child) {
9576                        Some(child)
9577                    } else {
9578                        None
9579                    };
9580                    let Some(declarator) = declarator else {
9581                        continue;
9582                    };
9583                    if declarator.kind() == "function_declarator"
9584                        && extract_variable_name(declarator, ctx.source)
9585                            .is_some_and(|name| name == receiver_name)
9586                        && function_declarator_parameters_have_known_types(declarator, ctx)
9587                        && !constructor_style_local_declaration(
9588                            ctx.visibility,
9589                            ctx.file,
9590                            ctx.source,
9591                            declarator,
9592                            type_text,
9593                            &ctx.bindings,
9594                        )
9595                    {
9596                        return true;
9597                    }
9598                }
9599            }
9600            return false;
9601        }
9602        current = parent;
9603    }
9604    false
9605}
9606
9607fn function_declarator_parameters_have_known_types(
9608    declarator: Node<'_>,
9609    ctx: &ScanCtx<'_>,
9610) -> bool {
9611    let Some(parameters) = declarator.child_by_field_name("parameters") else {
9612        return false;
9613    };
9614    let mut cursor = parameters.walk();
9615    parameters.named_children(&mut cursor).all(|parameter| {
9616        if !matches!(
9617            parameter.kind(),
9618            "parameter_declaration" | "optional_parameter_declaration"
9619        ) {
9620            return false;
9621        }
9622        let Some(type_node) = parameter
9623            .child_by_field_name("type")
9624            .or_else(|| first_type_child(parameter))
9625        else {
9626            return false;
9627        };
9628        type_node.kind() == "primitive_type"
9629            || ctx
9630                .visibility
9631                .resolve_type_node_result(ctx.file, type_node, ctx.source)
9632                .ok()
9633                .flatten()
9634                .is_some()
9635    })
9636}
9637
9638#[derive(Clone, Copy, PartialEq, Eq)]
9639enum QualifiedOwnerResolution {
9640    Target,
9641    NonTarget,
9642    Unresolved,
9643}
9644
9645#[derive(Clone)]
9646pub enum LexicalScopeResolution {
9647    Resolved(Vec<String>),
9648    Ambiguous,
9649    Missing,
9650}
9651
9652/// One scan's memo of lexical scope reconstructions for one file, keyed by
9653/// the reconstruction's anchor range and flags, with the file's recovered
9654/// namespace regions that the key and the reconstruction both read.
9655pub struct LexicalScopeCache {
9656    resolutions: RefCell<HashMap<(usize, usize, bool, bool), LexicalScopeResolution>>,
9657    orphaned: Arc<OrphanedNamespaceScopeIndex>,
9658}
9659
9660impl LexicalScopeCache {
9661    fn new(visibility: &VisibilityIndex<'_>, file: &ProjectFile) -> Self {
9662        Self {
9663            resolutions: RefCell::new(HashMap::default()),
9664            orphaned: orphaned_namespace_scopes(visibility, file),
9665        }
9666    }
9667}
9668
9669/// The namespaces parse recovery dropped from `file`, memoized on the
9670/// analyzer (issue #1537).
9671fn orphaned_namespace_scopes(
9672    visibility: &VisibilityIndex<'_>,
9673    file: &ProjectFile,
9674) -> Arc<OrphanedNamespaceScopeIndex> {
9675    visibility
9676        .cpp()
9677        .orphaned_namespace_scopes(visibility.token(), file)
9678}
9679
9680fn qualified_owner_matches(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9681    qualified_owner_resolution(node, ctx) == QualifiedOwnerResolution::Target
9682}
9683
9684fn qualified_owner_is_known_non_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9685    qualified_owner_resolution(node, ctx) == QualifiedOwnerResolution::NonTarget
9686}
9687
9688fn is_structurally_qualified(node: Node<'_>) -> bool {
9689    matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
9690        && qualified_name_has_concrete_scope_separators(node)
9691}
9692
9693fn qualified_owner_resolution(node: Node<'_>, ctx: &ScanCtx<'_>) -> QualifiedOwnerResolution {
9694    let Some(target_owner) = ctx.spec.owner.as_ref() else {
9695        return QualifiedOwnerResolution::Unresolved;
9696    };
9697    let Some((components, global)) = qualified_callable_owner_components(node, ctx.source) else {
9698        return QualifiedOwnerResolution::Unresolved;
9699    };
9700    // A malformed wrapper can make the parser-derived enclosing owner look
9701    // like the lexical namespace (for example tinyxml2's macro-prefixed
9702    // XMLHandle declarations). Recover the target namespace only while this
9703    // function owns scope reconstruction. An explicit recovered scope is
9704    // authoritative and enters the scoped resolver directly.
9705    if !global
9706        && !matches!(
9707            enclosing_lexical_scope_components(
9708                node,
9709                &ctx.analyzer,
9710                ctx.visibility,
9711                ctx.file,
9712                ctx.source,
9713            ),
9714            LexicalScopeResolution::Resolved(_)
9715        )
9716    {
9717        return QualifiedOwnerResolution::Unresolved;
9718    }
9719    match resolve_type_components_lexically_at_for_target_with_scope_cache(
9720        node,
9721        &components,
9722        global,
9723        &ctx.analyzer,
9724        ctx.visibility,
9725        &ctx.ordinary_type_imports,
9726        ctx.file,
9727        ctx.source,
9728        target_owner,
9729        false,
9730        Some(&ctx.lexical_scope_cache),
9731    ) {
9732        LexicalTypeResolution::Resolved { unit: owner, .. } => {
9733            if receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx) {
9734                return QualifiedOwnerResolution::Target;
9735            }
9736            match cached_declaring_member_owner(&owner, ctx) {
9737                EnclosingMemberOwnerResolution::Owner(declaring_owner)
9738                    if receiver_owner_matches_target(
9739                        &declaring_owner,
9740                        target_owner,
9741                        node.start_byte(),
9742                        ctx,
9743                    ) =>
9744                {
9745                    QualifiedOwnerResolution::Target
9746                }
9747                EnclosingMemberOwnerResolution::Owner(declaring_owner)
9748                    if receiver_owner_is_known_non_target(
9749                        &declaring_owner,
9750                        target_owner,
9751                        node.start_byte(),
9752                        ctx,
9753                    ) =>
9754                {
9755                    QualifiedOwnerResolution::NonTarget
9756                }
9757                EnclosingMemberOwnerResolution::Owner(_)
9758                | EnclosingMemberOwnerResolution::Ambiguous => QualifiedOwnerResolution::Unresolved,
9759                EnclosingMemberOwnerResolution::Missing
9760                    if same_visible_symbol(&owner, target_owner) =>
9761                {
9762                    QualifiedOwnerResolution::Unresolved
9763                }
9764                EnclosingMemberOwnerResolution::Missing => QualifiedOwnerResolution::NonTarget,
9765            }
9766        }
9767        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => {
9768            QualifiedOwnerResolution::Unresolved
9769        }
9770    }
9771}
9772
9773fn qualified_callable_owner_components(
9774    node: Node<'_>,
9775    source: &str,
9776) -> Option<(Vec<String>, bool)> {
9777    if !matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
9778        || !qualified_name_has_concrete_scope_separators(node)
9779    {
9780        return None;
9781    }
9782    let owner = qualified_owner_components(node, source)?;
9783    Some((owner.names, owner.global))
9784}
9785
9786fn type_reference_components(node: Node<'_>, source: &str) -> Option<(Vec<String>, bool)> {
9787    if !matches!(
9788        node.kind(),
9789        "identifier"
9790            | "type_identifier"
9791            | "namespace_identifier"
9792            | "qualified_identifier"
9793            | "scoped_identifier"
9794            | "scoped_type_identifier"
9795            | "template_type"
9796            | "template_function"
9797    ) {
9798        return None;
9799    }
9800    let components = cpp_type_name_components(node, source)?;
9801    (!components.is_empty()).then_some((components, is_globally_qualified_cpp_name(node)))
9802}
9803
9804pub fn enclosing_namespace_components(node: Node<'_>, source: &str) -> Vec<String> {
9805    let mut namespaces = Vec::new();
9806    for parent in enclosing_cpp_namespace_nodes(node) {
9807        if let Some(name) = parent.child_by_field_name("name") {
9808            let mut components = Vec::new();
9809            if append_cpp_name_components(name, source, &mut components).is_some() {
9810                namespaces.push(components);
9811            }
9812        }
9813    }
9814    namespaces.into_iter().flatten().collect()
9815}
9816
9817pub fn enclosing_lexical_scope_components(
9818    node: Node<'_>,
9819    analyzer: &CppGraphSource<'_>,
9820    visibility: &VisibilityIndex<'_>,
9821    file: &ProjectFile,
9822    source: &str,
9823) -> LexicalScopeResolution {
9824    enclosing_lexical_scope_components_with_unresolved_owner(
9825        node,
9826        analyzer,
9827        visibility,
9828        file,
9829        source,
9830        false,
9831        false,
9832        &orphaned_namespace_scopes(visibility, file),
9833    )
9834}
9835
9836#[allow(clippy::too_many_arguments)]
9837fn cached_enclosing_lexical_scope_components_with_unresolved_owner(
9838    node: Node<'_>,
9839    analyzer: &CppGraphSource<'_>,
9840    visibility: &VisibilityIndex<'_>,
9841    file: &ProjectFile,
9842    source: &str,
9843    allow_structured_unresolved_owner: bool,
9844    ignore_function_owner: bool,
9845    cache: Option<&LexicalScopeCache>,
9846) -> LexicalScopeResolution {
9847    let Some(cache) = cache else {
9848        return enclosing_lexical_scope_components_with_unresolved_owner(
9849            node,
9850            analyzer,
9851            visibility,
9852            file,
9853            source,
9854            allow_structured_unresolved_owner,
9855            ignore_function_owner,
9856            &orphaned_namespace_scopes(visibility, file),
9857        );
9858    };
9859    let orphaned = &cache.orphaned;
9860    let (anchor_start, anchor_end) = lexical_scope_cache_anchor(node);
9861    // A namespace body or translation unit anchor spans every recovered
9862    // region among its children, whose scopes differ; the region bounds keep
9863    // the key exact there and leave an anchor inside one region unchanged.
9864    let (anchor_start, anchor_end) = match orphaned.region_at(node.start_byte()) {
9865        Some(region) => (anchor_start.max(region.start), anchor_end.min(region.end)),
9866        None => (anchor_start, anchor_end),
9867    };
9868    let key = (
9869        anchor_start,
9870        anchor_end,
9871        allow_structured_unresolved_owner,
9872        ignore_function_owner,
9873    );
9874    if let Some(cached) = cache.resolutions.borrow().get(&key).cloned() {
9875        return cached;
9876    }
9877    let resolved = enclosing_lexical_scope_components_with_unresolved_owner(
9878        node,
9879        analyzer,
9880        visibility,
9881        file,
9882        source,
9883        allow_structured_unresolved_owner,
9884        ignore_function_owner,
9885        orphaned,
9886    );
9887    cache.resolutions.borrow_mut().insert(key, resolved.clone());
9888    resolved
9889}
9890
9891fn lexical_scope_cache_anchor(node: Node<'_>) -> (usize, usize) {
9892    let mut current = node;
9893    loop {
9894        if matches!(
9895            current.kind(),
9896            "function_definition"
9897                | "class_specifier"
9898                | "struct_specifier"
9899                | "union_specifier"
9900                | "namespace_definition"
9901                | "translation_unit"
9902        ) {
9903            return (current.start_byte(), current.end_byte());
9904        }
9905        let Some(parent) = current.parent() else {
9906            return (current.start_byte(), current.end_byte());
9907        };
9908        current = parent;
9909    }
9910}
9911
9912#[allow(clippy::too_many_arguments)]
9913fn enclosing_lexical_scope_components_with_unresolved_owner(
9914    node: Node<'_>,
9915    analyzer: &CppGraphSource<'_>,
9916    visibility: &VisibilityIndex<'_>,
9917    file: &ProjectFile,
9918    source: &str,
9919    allow_structured_unresolved_owner: bool,
9920    ignore_function_owner: bool,
9921    orphaned: &OrphanedNamespaceScopeIndex,
9922) -> LexicalScopeResolution {
9923    #[cfg(any(test, feature = "test-support"))]
9924    LEXICAL_SCOPE_RECONSTRUCTIONS_FOR_TEST.with(|count| count.set(count.get() + 1));
9925    // One ancestor climb collects the namespace chain, the class chain, the
9926    // nearest function definition and both displaced-class-shape facts.
9927    // `Node::parent` re-descends from the root on every call (tree-sitter
9928    // 0.24+), so the four separate climbs this replaces each cost another
9929    // near-full-AST scan per reconstruction on a large flat file (#1927).
9930    let mut namespaces = Vec::new();
9931    let mut classes = Vec::new();
9932    let mut function_definition = None;
9933    let mut displaced_class_scope = false;
9934    let mut current = node.parent();
9935    while let Some(parent) = current {
9936        match parent.kind() {
9937            "namespace_definition" => {
9938                if let Some(name) = parent.child_by_field_name("name") {
9939                    let mut components = Vec::new();
9940                    if append_cpp_name_components(name, source, &mut components).is_some() {
9941                        namespaces.push((
9942                            parent.start_byte(),
9943                            components,
9944                            namespace_definition_has_real_braces(parent),
9945                        ));
9946                    }
9947                }
9948            }
9949            "class_specifier" | "struct_specifier" | "union_specifier" => {
9950                if let Some(name) = parent.child_by_field_name("name") {
9951                    let mut components = Vec::new();
9952                    if append_cpp_name_components(name, source, &mut components).is_some() {
9953                        classes.push(components);
9954                    }
9955                }
9956            }
9957            "function_definition" => {
9958                if function_definition.is_none() {
9959                    function_definition = Some(parent);
9960                }
9961                displaced_class_scope = displaced_class_scope
9962                    || parent.child_by_field_name("type").is_some_and(|type_node| {
9963                        matches!(
9964                            type_node.kind(),
9965                            "class_specifier" | "struct_specifier" | "union_specifier"
9966                        )
9967                    })
9968                    || is_malformed_wrapper_function_definition(parent);
9969            }
9970            _ => {}
9971        }
9972        current = parent.parent();
9973    }
9974    namespaces.reverse();
9975    // The parsed chain can stop short of the namespaces tree-sitter's error
9976    // recovery closed early; the orphaned index restores them (#1537).
9977    let namespace = orphaned.restore_enclosing_namespaces(namespaces, node.start_byte());
9978    let mut scope = namespace.clone();
9979    // A malformed namespace-sentinel wrapper can parse `namespace a::b` as a
9980    // qualified function declarator. It is recovery scaffolding, not a real
9981    // callable owner, and must not overwrite the indexed class scope retained
9982    // by the wrapper body (#2249).
9983    let has_qualified_function_owner = function_definition
9984        .filter(|function| !is_malformed_wrapper_function_definition(*function))
9985        .and_then(function_definition_owner_lookup_node)
9986        .is_some_and(|owner| {
9987            is_structurally_qualified(owner) && !is_macro_decorated_function_owner(owner)
9988        });
9989    let indexed_scope = displaced_class_scope
9990        .then(|| {
9991            indexed_structural_class_scope(visibility, file, node, source)
9992                .or_else(|| indexed_enclosing_owner_scope(analyzer, visibility, file, node))
9993        })
9994        .flatten()
9995        .or_else(|| {
9996            // A qualified out-of-line definition can lose its class owner from
9997            // the parser tree when a namespace sentinel or export macro wraps
9998            // the declaration.  Recover the indexed owner scope up front so
9999            // all unqualified type references in the body see the same class
10000            // boundary as C++ lookup, including aliases in parameters and
10001            // local declarations (not only template-argument leaves).
10002            (has_qualified_function_owner && function_definition.is_some())
10003                .then(|| indexed_enclosing_owner_scope(analyzer, visibility, file, node))
10004                .flatten()
10005                .filter(|indexed| {
10006                    qualified_owner_scope_is_recoverable(
10007                        indexed,
10008                        &namespace,
10009                        &classes,
10010                        function_definition
10011                            .and_then(function_definition_owner_lookup_node)
10012                            .and_then(|owner| qualified_callable_owner_components(owner, source))
10013                            .map(|(components, _)| components),
10014                    )
10015                })
10016        })
10017        .or_else(|| {
10018            // A nested class declaration can likewise lose one of its outer
10019            // class ancestors from the CST.  Prefer the exact indexed
10020            // structural class scope. Its same-file declaration range and
10021            // exact template-id match already prove the owner, including a
10022            // specialization whose parser component retains only the primary
10023            // name. Keep the suffix guard for graph-only recovery, which lacks
10024            // that direct syntax-range proof.
10025            indexed_structural_class_scope(visibility, file, node, source).or_else(|| {
10026                indexed_enclosing_owner_scope(analyzer, visibility, file, node).filter(|indexed| {
10027                    qualified_owner_scope_is_recoverable(indexed, &namespace, &classes, None)
10028                })
10029            })
10030        })
10031        .or_else(|| {
10032            // Retain the existing indexed lexical-scope recovery for
10033            // unqualified function bodies.  It is intentionally last so a
10034            // canonical class owner wins whenever one is available.
10035            (classes.is_empty() && function_definition.is_some() && !has_qualified_function_owner)
10036                .then(|| indexed_enclosing_lexical_scope(analyzer, file, node))
10037                .flatten()
10038                .filter(|indexed| indexed.len() > namespace.len())
10039        });
10040    if let Some(indexed_scope) = indexed_scope.as_ref() {
10041        // A macro-displaced namespace can leave the parser with the real class
10042        // body but no namespace ancestor. Prefer the structural class match;
10043        // partial specializations whose structured name cannot round-trip use
10044        // the exact indexed enclosing-owner chain instead.
10045        scope = indexed_scope.clone();
10046        classes.clear();
10047    }
10048
10049    if !ignore_function_owner
10050        && has_qualified_function_owner
10051        && let Some(function) = function_definition.and_then(function_definition_owner_lookup_node)
10052    {
10053        let Some((owner, global)) = qualified_callable_owner_components(function, source) else {
10054            return LexicalScopeResolution::Missing;
10055        };
10056        // Resolve the out-of-line owner from the parser namespace before the
10057        // provisional indexed parent can influence the answer. Per-file
10058        // extraction can assign the first same-depth using namespace to a
10059        // bare owner. The structured using resolver instead selects the
10060        // namespace whose visible class has the owner name (#1838).
10061        let imports = visibility.ordinary_type_import_cell(file);
10062        let owner_resolution = resolve_type_components_lexically_at_scoped(
10063            function,
10064            &owner,
10065            global,
10066            analyzer,
10067            visibility,
10068            &imports,
10069            file,
10070            source,
10071            None,
10072            false,
10073            false,
10074            false,
10075            namespace.clone(),
10076        );
10077        match owner_resolution {
10078            LexicalTypeResolution::Resolved {
10079                unit, components, ..
10080            } if is_indexed_class_owner(analyzer, &unit) => {
10081                scope = components;
10082                classes.clear();
10083            }
10084            LexicalTypeResolution::Ambiguous => return LexicalScopeResolution::Ambiguous,
10085            LexicalTypeResolution::Resolved { .. } | LexicalTypeResolution::Missing => {
10086                match visibility
10087                    .resolve_type_components_lexically(analyzer, file, &owner, global, &scope)
10088                {
10089                    LexicalTypeResolution::Resolved { components, .. } => scope = components,
10090                    LexicalTypeResolution::Ambiguous => return LexicalScopeResolution::Ambiguous,
10091                    LexicalTypeResolution::Missing if allow_structured_unresolved_owner => {
10092                        if let Some(indexed) = indexed_scope.as_ref().filter(|indexed| {
10093                            qualified_owner_scope_is_recoverable(
10094                                indexed,
10095                                &namespace,
10096                                &classes,
10097                                Some(owner.clone()),
10098                            )
10099                        }) {
10100                            scope = indexed.clone();
10101                        } else {
10102                            scope = if global || owner.starts_with(&namespace) {
10103                                owner
10104                            } else {
10105                                let mut relative = namespace;
10106                                relative.extend(owner);
10107                                relative
10108                            };
10109                        }
10110                    }
10111                    LexicalTypeResolution::Missing => {
10112                        // Structural lexical resolution cannot see an owner class that
10113                        // is reachable only through an in-scope `using namespace`
10114                        // directive, so it would otherwise hard-fail here. The indexed
10115                        // definition already carries the true fully-qualified owner
10116                        // (its package reflects the directive), so recover the real
10117                        // enclosing scope from the analyzer graph -- exactly the scope
10118                        // chain real C++ unqualified lookup traverses. Only the strict
10119                        // callers reach this arm; the best-effort callers above keep
10120                        // their existing structural guess (and its query profile).
10121                        match indexed_enclosing_owner_scope(analyzer, visibility, file, node)
10122                            .or_else(|| {
10123                                indexed_namespace_qualified_scope(
10124                                    analyzer, visibility, file, node, &owner,
10125                                )
10126                            }) {
10127                            Some(indexed) => scope = indexed,
10128                            None => return LexicalScopeResolution::Missing,
10129                        }
10130                    }
10131                }
10132            }
10133        }
10134    }
10135
10136    classes.reverse();
10137    scope.extend(classes.into_iter().flatten());
10138    LexicalScopeResolution::Resolved(scope)
10139}
10140
10141fn has_recovered_class_shape_ancestor(node: Node<'_>) -> bool {
10142    let mut current = node.parent();
10143    while let Some(parent) = current {
10144        if parent.kind() == "function_definition"
10145            && parent.child_by_field_name("type").is_some_and(|type_node| {
10146                matches!(
10147                    type_node.kind(),
10148                    "class_specifier" | "struct_specifier" | "union_specifier"
10149                )
10150            })
10151        {
10152            return true;
10153        }
10154        current = parent.parent();
10155    }
10156    false
10157}
10158
10159fn has_malformed_wrapper_function_definition_ancestor(node: Node<'_>) -> bool {
10160    let mut current = node.parent();
10161    while let Some(parent) = current {
10162        if parent.kind() == "function_definition"
10163            && is_malformed_wrapper_function_definition(parent)
10164        {
10165            return true;
10166        }
10167        current = parent.parent();
10168    }
10169    false
10170}
10171
10172/// Whether an errored function definition has a non-function wrapper declarator.
10173pub fn is_malformed_wrapper_function_definition(node: Node<'_>) -> bool {
10174    node.has_error()
10175        && node
10176            .child_by_field_name("declarator")
10177            .is_some_and(|declarator| {
10178                declarator.kind() != "function_declarator"
10179                    && first_descendant_of_kind(declarator, "function_declarator").is_none()
10180            })
10181}
10182
10183/// Tree-sitter can make an attribute/nullability macro look like the namespace
10184/// component of a qualified function owner when it appears between the return
10185/// type and the declarator (for example `CordRep* absl_nullable VerifyTree`).
10186/// The recovered owner is not a C++ lexical owner, so callers resolving the
10187/// ordinary return/parameter type must retain the surrounding namespace scope.
10188fn is_macro_decorated_function_owner(node: Node<'_>) -> bool {
10189    node.child_by_field_name("scope")
10190        .and_then(|scope| recovered_macro_decorated_type_node(scope))
10191        .is_some()
10192}
10193
10194fn indexed_structural_class_scope(
10195    visibility: &VisibilityIndex<'_>,
10196    file: &ProjectFile,
10197    node: Node<'_>,
10198    source: &str,
10199) -> Option<Vec<String>> {
10200    let mut current = node.parent();
10201    while let Some(parent) = current {
10202        if matches!(
10203            parent.kind(),
10204            "class_specifier" | "struct_specifier" | "union_specifier"
10205        ) {
10206            return visibility.indexed_structural_class_scope(file, parent, source);
10207        }
10208        current = parent.parent();
10209    }
10210    None
10211}
10212
10213/// Check that an indexed owner scope is a structured completion of the parser
10214/// scope rather than an unrelated same-spelled declaration.
10215///
10216/// Error recovery around C++ namespace sentinels can preserve only a subset of
10217/// the namespace/class chain.  The indexed definition still carries the full
10218/// owner path, so require every surviving parser component to occur in order
10219/// and require any explicit qualified function owner to be the terminal
10220/// suffix.  An empty parser scope is accepted only with that qualified-owner
10221/// suffix evidence; a lone top-level short name is not evidence that a
10222/// namespace was lost.
10223fn qualified_owner_scope_is_recoverable(
10224    indexed: &[String],
10225    namespace: &[String],
10226    classes: &[Vec<String>],
10227    qualified_owner: Option<Vec<String>>,
10228) -> bool {
10229    if let Some(owner) = qualified_owner {
10230        if indexed.len() <= owner.len() || !indexed.ends_with(&owner) {
10231            return false;
10232        }
10233        // A malformed namespace sentinel can erase every parser namespace
10234        // ancestor.  The indexed enclosing callable still provides an
10235        // authoritative class owner, so the qualified owner suffix itself is
10236        // enough evidence in that case.  When namespace components survived,
10237        // retain the stricter subsequence check below.
10238        if namespace.is_empty() {
10239            return true;
10240        }
10241        if indexed.len() <= namespace.len() {
10242            return false;
10243        }
10244        return super::cpp_namespace_path_is_ordered_subsequence(namespace, indexed);
10245    }
10246    let class_components = classes.iter().flatten().cloned().collect::<Vec<_>>();
10247    if !class_components.is_empty() {
10248        return indexed.len() > class_components.len() && indexed.ends_with(&class_components);
10249    }
10250    if namespace.is_empty() || indexed.len() <= namespace.len() {
10251        return false;
10252    }
10253    super::cpp_namespace_path_is_ordered_subsequence(namespace, indexed)
10254}
10255
10256/// Whether `unit` is a real (non-alias) class owner. A `using` alias never
10257/// counts as the true lexical owner recovered from the indexed graph.
10258fn is_indexed_class_owner(analyzer: &CppGraphSource<'_>, unit: &CodeUnit) -> bool {
10259    unit.is_class()
10260        && !analyzer
10261            .type_alias_provider()
10262            .is_some_and(|provider| provider.is_type_alias(unit))
10263}
10264
10265/// Recover the enclosing member's true lexical scope from the *indexed*
10266/// definition when structural resolution cannot see the owner class.
10267///
10268/// An out-of-line member defined at file scope (`int HTMLLayout::method()
10269/// {...}`) whose owner class is reachable only through an in-scope `using
10270/// namespace X;` directive cannot be resolved by `resolve_type_components_
10271/// lexically`, which walks structural lexical tiers and never consults
10272/// using-directives. The definition itself, however, is indexed with its true
10273/// fully-qualified identity (its package already reflects the directive), so
10274/// the analyzer graph knows the real owner. Walk from the reference's indexed
10275/// enclosing code unit up to the innermost enclosing class and return that
10276/// class's fully-qualified scope components (e.g. `["log4cxx", "HTMLLayout"]`)
10277/// -- exactly the scope chain C++ unqualified lookup traverses.
10278fn indexed_enclosing_owner_scope(
10279    analyzer: &CppGraphSource<'_>,
10280    visibility: &VisibilityIndex<'_>,
10281    file: &ProjectFile,
10282    node: Node<'_>,
10283) -> Option<Vec<String>> {
10284    visibility.indexed_enclosing_owner_scope(analyzer, file, node)
10285}
10286
10287/// Recover the lexical scope of an out-of-line definition whose syntactic
10288/// qualifier names a *namespace* rather than a class (`void out::target(int)
10289/// {...}` written at file scope, issue #3096).
10290///
10291/// `indexed_enclosing_owner_scope` looks for an enclosing *class*, so it finds
10292/// nothing here and the strict caller would fail closed for every unqualified
10293/// reference in the body. C++ unqualified lookup inside such a definition
10294/// proceeds from the named namespace outward, exactly as inside a `namespace
10295/// out { ... }` block, and the indexed definition already carries that scope
10296/// (`["out"]` for `out::target`).
10297///
10298/// Take it only when a namespace of that name is visible from the file and the
10299/// indexed scope ends with the syntactic qualifier. A qualifier naming a class
10300/// the graph does not hold (`void MissingContainer::call()`) has no such
10301/// namespace, so it still fails closed -- and it is rejected by the in-memory
10302/// visibility index, before any indexed enclosing-unit query.
10303fn indexed_namespace_qualified_scope(
10304    analyzer: &CppGraphSource<'_>,
10305    visibility: &VisibilityIndex<'_>,
10306    file: &ProjectFile,
10307    node: Node<'_>,
10308    owner: &[String],
10309) -> Option<Vec<String>> {
10310    let name = owner.last().expect("a qualified owner has one component");
10311    if !visibility
10312        .visible_identifier_candidates(file, name)
10313        .any(|unit| unit.is_module())
10314    {
10315        return None;
10316    }
10317    let indexed = indexed_enclosing_lexical_scope(analyzer, file, node)?;
10318    indexed.ends_with(owner).then_some(indexed)
10319}
10320
10321fn cached_indexed_enclosing_class_owner(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
10322    let start = enclosing_context(node, ctx).enclosing?;
10323    brokk_bifrost_core::analyzer::usages::common::enclosing_owner_chain(start, |unit| {
10324        ctx.analyzer.parent_of(unit)
10325    })
10326    .find(|unit| is_indexed_class_owner(&ctx.analyzer, unit))
10327}
10328
10329pub fn resolve_type_node_lexically(
10330    node: Node<'_>,
10331    analyzer: &CppGraphSource<'_>,
10332    visibility: &VisibilityIndex<'_>,
10333    ordinary_type_imports: &OrdinaryTypeImportCell,
10334    file: &ProjectFile,
10335    source: &str,
10336) -> LexicalTypeResolution {
10337    let Some((components, global)) = type_reference_components(node, source) else {
10338        return LexicalTypeResolution::Missing;
10339    };
10340    let resolution = resolve_type_components_lexically_at(
10341        node,
10342        &components,
10343        global,
10344        analyzer,
10345        visibility,
10346        ordinary_type_imports,
10347        file,
10348        source,
10349    );
10350    if !is_cpp_template_argument_type_leaf(node) {
10351        return resolution;
10352    }
10353
10354    // Error recovery can detach a member function from its class while
10355    // leaving an unqualified type argument (for example `error_type` in
10356    // `expected<..., error_type>`). The normal structural scope then lacks
10357    // the class owner and resolves the wrong same-spelled alias, or fails
10358    // closed. The indexed enclosing unit still carries the authoritative
10359    // class scope; retry only this narrowly-shaped leaf with that scope.
10360    let Some(indexed_scope) = indexed_enclosing_lexical_scope(analyzer, file, node) else {
10361        return resolution;
10362    };
10363    let namespace_scope = enclosing_namespace_components(node, source);
10364    if indexed_scope.len() <= namespace_scope.len() {
10365        return resolution;
10366    }
10367    let indexed = visibility.resolve_type_components_lexically(
10368        analyzer,
10369        file,
10370        &components,
10371        global,
10372        &indexed_scope,
10373    );
10374    match indexed {
10375        LexicalTypeResolution::Resolved { ref unit, .. }
10376            if !visibility
10377                .external_type_candidate_visible_in_context(analyzer, file, unit, node) =>
10378        {
10379            resolution
10380        }
10381        LexicalTypeResolution::Resolved { .. } => indexed,
10382        _ => resolution,
10383    }
10384}
10385
10386#[allow(clippy::too_many_arguments)]
10387pub fn resolve_type_node_lexically_for_target(
10388    node: Node<'_>,
10389    analyzer: &CppGraphSource<'_>,
10390    visibility: &VisibilityIndex<'_>,
10391    ordinary_type_imports: &OrdinaryTypeImportCell,
10392    file: &ProjectFile,
10393    source: &str,
10394    target: &CodeUnit,
10395    scope_cache: Option<&LexicalScopeCache>,
10396    recovered_scope: Option<&[String]>,
10397) -> LexicalTypeResolution {
10398    let Some((reference_components, global)) = type_reference_components(node, source) else {
10399        return LexicalTypeResolution::Missing;
10400    };
10401    let terminal = reference_components
10402        .last()
10403        .expect("type reference components are non-empty");
10404    if !visibility.coarse_unqualified_type_reference_may_resolve(file, terminal) {
10405        return LexicalTypeResolution::Missing;
10406    }
10407    let template_arguments = cpp_template_reference_arguments(node, source);
10408    let selects_concrete_specialization =
10409        template_arguments.is_some() && visibility.is_template_specialization(target);
10410    if !selects_concrete_specialization
10411        && !visibility.structured_type_reference_may_resolve_to_target(
10412            analyzer,
10413            file,
10414            std::slice::from_ref(terminal),
10415            false,
10416            &[],
10417            target,
10418        )
10419    {
10420        return LexicalTypeResolution::Missing;
10421    }
10422    if let Some(arguments) = template_arguments.as_ref() {
10423        let alias_resolution = if let Some(recovered_scope) = recovered_scope {
10424            resolve_type_components_lexically_at_preserving_alias_with_recovered_scope(
10425                node,
10426                &reference_components,
10427                global,
10428                analyzer,
10429                visibility,
10430                ordinary_type_imports,
10431                file,
10432                source,
10433                recovered_scope,
10434            )
10435        } else {
10436            resolve_type_components_lexically_at_preserving_alias_with_scope_cache(
10437                node,
10438                &reference_components,
10439                global,
10440                analyzer,
10441                visibility,
10442                ordinary_type_imports,
10443                file,
10444                source,
10445                scope_cache,
10446            )
10447        };
10448        return match alias_resolution {
10449            LexicalTypeResolution::Resolved {
10450                unit,
10451                components,
10452                candidates,
10453            } if visibility.template_alias_arguments_preserve_target(
10454                analyzer, file, &unit, arguments, target,
10455            ) =>
10456            {
10457                LexicalTypeResolution::Resolved {
10458                    unit: target.clone(),
10459                    components,
10460                    candidates,
10461                }
10462            }
10463            LexicalTypeResolution::Resolved {
10464                unit,
10465                components,
10466                candidates,
10467            } => match visibility.resolve_template_arguments(file, unit.clone(), arguments) {
10468                Ok(resolved_unit) => {
10469                    let target_guided = (!same_visible_symbol(&resolved_unit, target))
10470                        .then(|| {
10471                            target_guided_malformed_template_alias_resolution(
10472                                node,
10473                                analyzer,
10474                                visibility,
10475                                file,
10476                                arguments,
10477                                &reference_components,
10478                                target,
10479                            )
10480                        })
10481                        .flatten();
10482                    target_guided.unwrap_or(LexicalTypeResolution::Resolved {
10483                        unit: resolved_unit,
10484                        components,
10485                        candidates,
10486                    })
10487                }
10488                Err(_) => LexicalTypeResolution::Ambiguous,
10489            },
10490            LexicalTypeResolution::Missing => {
10491                let target_preserving = if let Some(recovered_scope) = recovered_scope {
10492                    resolve_type_components_lexically_at_for_target_with_recovered_scope(
10493                        node,
10494                        &reference_components,
10495                        global,
10496                        analyzer,
10497                        visibility,
10498                        ordinary_type_imports,
10499                        file,
10500                        source,
10501                        target,
10502                        true,
10503                        recovered_scope,
10504                    )
10505                } else {
10506                    resolve_type_components_lexically_at_for_target_with_scope_cache(
10507                        node,
10508                        &reference_components,
10509                        global,
10510                        analyzer,
10511                        visibility,
10512                        ordinary_type_imports,
10513                        file,
10514                        source,
10515                        target,
10516                        true,
10517                        scope_cache,
10518                    )
10519                };
10520                match target_preserving {
10521                    LexicalTypeResolution::Resolved {
10522                        unit: _,
10523                        components,
10524                        candidates,
10525                    } if template_reference_candidates_select_target(
10526                        node,
10527                        &candidates,
10528                        analyzer,
10529                        visibility,
10530                        file,
10531                        source,
10532                        target,
10533                    ) =>
10534                    {
10535                        LexicalTypeResolution::Resolved {
10536                            unit: target.clone(),
10537                            components,
10538                            candidates,
10539                        }
10540                    }
10541                    _ => target_guided_malformed_template_alias_resolution(
10542                        node,
10543                        analyzer,
10544                        visibility,
10545                        file,
10546                        arguments,
10547                        &reference_components,
10548                        target,
10549                    )
10550                    .unwrap_or(LexicalTypeResolution::Missing),
10551                }
10552            }
10553            LexicalTypeResolution::Ambiguous => LexicalTypeResolution::Ambiguous,
10554        };
10555    }
10556    let resolution = if let Some(recovered_scope) = recovered_scope {
10557        resolve_type_components_lexically_at_for_target_with_recovered_scope(
10558            node,
10559            &reference_components,
10560            global,
10561            analyzer,
10562            visibility,
10563            ordinary_type_imports,
10564            file,
10565            source,
10566            target,
10567            true,
10568            recovered_scope,
10569        )
10570    } else {
10571        resolve_type_components_lexically_at_for_target_with_scope_cache(
10572            node,
10573            &reference_components,
10574            global,
10575            analyzer,
10576            visibility,
10577            ordinary_type_imports,
10578            file,
10579            source,
10580            target,
10581            true,
10582            scope_cache,
10583        )
10584    };
10585    let resolution = if matches!(resolution, LexicalTypeResolution::Missing) {
10586        target_guided_qualified_namespace_function_type_resolution(
10587            node,
10588            &reference_components,
10589            global,
10590            analyzer,
10591            visibility,
10592            ordinary_type_imports,
10593            file,
10594            source,
10595            target,
10596        )
10597        .unwrap_or(resolution)
10598    } else {
10599        resolution
10600    };
10601    if !is_cpp_template_argument_type_leaf(node) {
10602        return resolution;
10603    }
10604
10605    // Preprocessor recovery can lift a member declaration out of its class
10606    // field list.  The unqualified template argument is then resolved from
10607    // the namespace only, even though the indexed enclosing callable still
10608    // identifies the class owner.  Retry this exact leaf against that
10609    // structured owner scope; ordinary type nodes must continue to use the
10610    // parser-derived lexical scope so unrelated same-spelled aliases remain
10611    // excluded.
10612    let Some(indexed_scope) = indexed_enclosing_lexical_scope(analyzer, file, node) else {
10613        return resolution;
10614    };
10615    let namespace_scope = enclosing_namespace_components(node, source);
10616    if indexed_scope.len() <= namespace_scope.len() {
10617        return resolution;
10618    }
10619    let indexed = visibility.resolve_type_components_lexically_for_target(
10620        analyzer,
10621        file,
10622        &reference_components,
10623        global,
10624        &indexed_scope,
10625        target,
10626    );
10627    match indexed {
10628        LexicalTypeResolution::Resolved {
10629            ref unit,
10630            ref candidates,
10631            ..
10632        } if (same_visible_symbol(unit, target)
10633            || candidates
10634                .iter()
10635                .any(|candidate| same_visible_symbol(candidate, target)))
10636            && visibility
10637                .external_type_candidate_visible_in_context(analyzer, file, unit, node) =>
10638        {
10639            indexed
10640        }
10641        _ => resolution,
10642    }
10643}
10644
10645/// Recover the lexical namespace of an out-of-line namespace function whose
10646/// relative qualifier is reachable through a `using namespace` directive.
10647///
10648/// Per-file declaration extraction can attach `void schema::consume(...)` to
10649/// the first visible namespace prefix when more than one using-directive is
10650/// active. A matching visible free-function declaration still proves the
10651/// complete namespace. Target-guided inverse lookup may use that namespace to
10652/// retry a parameter or body type, but only when the target lives in the same
10653/// namespace and the declaration's callable arity matches the definition.
10654#[allow(clippy::too_many_arguments)]
10655fn target_guided_qualified_namespace_function_type_resolution(
10656    node: Node<'_>,
10657    components: &[String],
10658    global: bool,
10659    analyzer: &CppGraphSource<'_>,
10660    visibility: &VisibilityIndex<'_>,
10661    ordinary_type_imports: &OrdinaryTypeImportCell,
10662    file: &ProjectFile,
10663    source: &str,
10664    target: &CodeUnit,
10665) -> Option<LexicalTypeResolution> {
10666    let function_definition = std::iter::successors(Some(node), |current| current.parent())
10667        .find(|current| current.kind() == "function_definition")?;
10668    let function = function_definition_name_node(function_definition)?;
10669    let (owner, owner_global) = qualified_callable_owner_components(function, source)?;
10670    let target_namespace = target.package_name();
10671    if target_namespace.is_empty() {
10672        return None;
10673    }
10674    let target_scope = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
10675        brokk_bifrost_core::analyzer::Language::Cpp,
10676        target_namespace,
10677    );
10678    if (owner_global && target_scope != owner) || (!owner_global && !target_scope.ends_with(&owner))
10679    {
10680        return None;
10681    }
10682
10683    let function_name = node_text(function_terminal_node(function), source);
10684    let definition_unit = canonical_callable_at_node(
10685        function_definition,
10686        analyzer,
10687        visibility,
10688        file,
10689        source,
10690        TargetKind::FreeFunction,
10691    )?;
10692    let definition_arity = cpp_callable_arity(analyzer, &definition_unit)?.total();
10693    let declaration_proves_namespace = visibility
10694        .visible_identifier_candidates(file, function_name)
10695        .filter(|candidate| {
10696            candidate.is_function()
10697                && type_owner_of(analyzer, candidate).is_none()
10698                && candidate.package_name() == target_namespace
10699        })
10700        .any(|candidate| {
10701            cpp_callable_arity(analyzer, candidate)
10702                .is_none_or(|known| known.accepts(definition_arity))
10703        });
10704    if !declaration_proves_namespace {
10705        return None;
10706    }
10707
10708    let resolution = resolve_type_components_lexically_at_scoped(
10709        node,
10710        components,
10711        global,
10712        analyzer,
10713        visibility,
10714        ordinary_type_imports,
10715        file,
10716        source,
10717        Some(target),
10718        true,
10719        false,
10720        false,
10721        target_scope,
10722    );
10723    match &resolution {
10724        LexicalTypeResolution::Resolved {
10725            unit, candidates, ..
10726        } if (same_visible_symbol(unit, target)
10727            || candidates
10728                .iter()
10729                .any(|candidate| same_visible_symbol(candidate, target)))
10730            && visibility
10731                .external_type_candidate_visible_in_context(analyzer, file, unit, node) =>
10732        {
10733            Some(resolution)
10734        }
10735        LexicalTypeResolution::Resolved { .. }
10736        | LexicalTypeResolution::Ambiguous
10737        | LexicalTypeResolution::Missing => None,
10738    }
10739}
10740
10741#[allow(clippy::too_many_arguments)]
10742fn target_guided_malformed_template_alias_resolution(
10743    node: Node<'_>,
10744    analyzer: &CppGraphSource<'_>,
10745    visibility: &VisibilityIndex<'_>,
10746    file: &ProjectFile,
10747    arguments: &[brokk_bifrost_core::analyzer::model::CppTemplateExpression],
10748    components: &[String],
10749    target: &CodeUnit,
10750) -> Option<LexicalTypeResolution> {
10751    if components.len() != 1 || !has_malformed_wrapper_function_definition_ancestor(node) {
10752        return None;
10753    }
10754
10755    let identifier = &components[0];
10756    let namespace =
10757        visibility.target_preserving_reference_namespace(analyzer, file, identifier, target)?;
10758    let namespace_name = namespace.join("::");
10759    let candidates = visibility
10760        .visible_identifier_candidates(file, identifier)
10761        .filter(|candidate| {
10762            cpp_namespace_for(candidate).unwrap_or_default() == namespace_name
10763                && visibility.type_candidate_may_be_visible_before_reference(
10764                    analyzer,
10765                    file,
10766                    candidate,
10767                    node.start_byte(),
10768                )
10769        })
10770        .cloned()
10771        .collect::<Vec<_>>();
10772    let first = candidates.first()?;
10773    if !candidates
10774        .iter()
10775        .all(|candidate| same_logical_symbol(first, candidate))
10776        || !candidates.iter().all(|candidate| {
10777            visibility.template_alias_arguments_preserve_target(
10778                analyzer, file, candidate, arguments, target,
10779            )
10780        })
10781    {
10782        return None;
10783    }
10784
10785    let mut resolved_components = namespace;
10786    resolved_components.push(identifier.clone());
10787    Some(LexicalTypeResolution::Resolved {
10788        unit: target.clone(),
10789        components: resolved_components,
10790        candidates,
10791    })
10792}
10793
10794fn resolve_type_node_lexically_for_target_without_visibility(
10795    node: Node<'_>,
10796    analyzer: &CppGraphSource<'_>,
10797    visibility: &VisibilityIndex<'_>,
10798    file: &ProjectFile,
10799    source: &str,
10800    target: &CodeUnit,
10801) -> LexicalTypeResolution {
10802    let Some((components, global)) = type_reference_components(node, source) else {
10803        return LexicalTypeResolution::Missing;
10804    };
10805    let lexical_scope = match enclosing_lexical_scope_components_with_unresolved_owner(
10806        node,
10807        analyzer,
10808        visibility,
10809        file,
10810        source,
10811        true,
10812        recovered_macro_decorated_declarator_type(node)
10813            == Some(RecoveredDeclaratorTypeContext::FunctionDefinition),
10814        &orphaned_namespace_scopes(visibility, file),
10815    ) {
10816        LexicalScopeResolution::Resolved(scope) => scope,
10817        LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
10818        LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
10819    };
10820    visibility.resolve_type_components_lexically_for_target(
10821        analyzer,
10822        file,
10823        &components,
10824        global,
10825        &lexical_scope,
10826        target,
10827    )
10828}
10829
10830fn type_node_has_exact_target_identity_without_visibility(
10831    node: Node<'_>,
10832    analyzer: &CppGraphSource<'_>,
10833    visibility: &VisibilityIndex<'_>,
10834    file: &ProjectFile,
10835    source: &str,
10836    target: &CodeUnit,
10837) -> bool {
10838    let Some((components, global)) = type_reference_components(node, source) else {
10839        return false;
10840    };
10841    let LexicalScopeResolution::Resolved(lexical_scope) =
10842        enclosing_lexical_scope_components_with_unresolved_owner(
10843            node,
10844            analyzer,
10845            visibility,
10846            file,
10847            source,
10848            true,
10849            recovered_macro_decorated_declarator_type(node)
10850                == Some(RecoveredDeclaratorTypeContext::FunctionDefinition),
10851            &orphaned_namespace_scopes(visibility, file),
10852        )
10853    else {
10854        return false;
10855    };
10856    let target_name = cpp_name_for(target);
10857    lexical_component_tiers(&components, global, &lexical_scope)
10858        .any(|qualified| qualified.join("::") == target_name)
10859}
10860
10861pub fn resolve_using_enum_declaration_owner(
10862    node: Node<'_>,
10863    analyzer: &CppGraphSource<'_>,
10864    visibility: &VisibilityIndex<'_>,
10865    ordinary_type_imports: &OrdinaryTypeImportCell,
10866    file: &ProjectFile,
10867    source: &str,
10868) -> LexicalTypeResolution {
10869    let Some(type_node) = using_enum_declaration_type_node(node) else {
10870        return LexicalTypeResolution::Missing;
10871    };
10872    let mut components = Vec::new();
10873    if append_cpp_name_components(type_node, source, &mut components).is_none()
10874        || components.is_empty()
10875    {
10876        return LexicalTypeResolution::Missing;
10877    }
10878    resolve_type_components_lexically_at(
10879        type_node,
10880        &components,
10881        is_globally_qualified_cpp_name(type_node),
10882        analyzer,
10883        visibility,
10884        ordinary_type_imports,
10885        file,
10886        source,
10887    )
10888}
10889
10890pub fn resolve_ordinary_using_declaration_owner(
10891    node: Node<'_>,
10892    analyzer: &CppGraphSource<'_>,
10893    visibility: &VisibilityIndex<'_>,
10894    file: &ProjectFile,
10895    source: &str,
10896) -> LexicalTypeResolution {
10897    let Some(type_node) = ordinary_using_declaration_type_node(node) else {
10898        return LexicalTypeResolution::Missing;
10899    };
10900    let mut components = Vec::new();
10901    if append_cpp_name_components(type_node, source, &mut components).is_none()
10902        || components.len() < 2
10903    {
10904        return LexicalTypeResolution::Missing;
10905    }
10906    let lexical_scope =
10907        match enclosing_lexical_scope_components(type_node, analyzer, visibility, file, source) {
10908            LexicalScopeResolution::Resolved(scope) => scope,
10909            LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
10910            LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
10911        };
10912    visibility.resolve_type_components_lexically(
10913        analyzer,
10914        file,
10915        &components,
10916        is_globally_qualified_cpp_name(type_node),
10917        &lexical_scope,
10918    )
10919}
10920
10921pub fn using_enum_declaration_type_node(node: Node<'_>) -> Option<Node<'_>> {
10922    (node.kind() == "using_declaration"
10923        && (0..node.child_count()).any(|index| {
10924            node.child(index)
10925                .is_some_and(|child| child.kind() == "enum")
10926        }))
10927    .then(|| node.named_child(0))
10928    .flatten()
10929}
10930
10931pub fn ordinary_using_declaration_type_node(node: Node<'_>) -> Option<Node<'_>> {
10932    (node.kind() == "using_declaration"
10933        && using_enum_declaration_type_node(node).is_none()
10934        && using_namespace_directive_name_node(node).is_none())
10935    .then(|| node.named_child(0))
10936    .flatten()
10937}
10938
10939/// Tree-sitter can recover `using ::absl::cord_internal::CordRep;` after an
10940/// undefined namespace-sentinel macro as a declaration whose type is the
10941/// all-caps sentinel and whose qualified declarator starts with a pseudo
10942/// `using` scope. The real imported name remains a structured qualified
10943/// identifier under that declarator. Recover only this exact CST envelope so
10944/// ordinary macro-decorated variables are not treated as imports.
10945fn recovered_macro_using_declaration_type_node<'tree>(
10946    node: Node<'tree>,
10947    source: &str,
10948) -> Option<(Node<'tree>, bool)> {
10949    if node.kind() != "declaration" {
10950        return None;
10951    }
10952    let macro_type = node.child_by_field_name("type")?;
10953    if macro_type.kind() != "type_identifier"
10954        || !cpp_export_macro_token(node_text(macro_type, source))
10955    {
10956        return None;
10957    }
10958    let declarator = node.child_by_field_name("declarator")?;
10959    if declarator.kind() != "qualified_identifier" {
10960        return None;
10961    }
10962    let scope = declarator.child_by_field_name("scope")?;
10963    if scope.kind() != "namespace_identifier" || node_text(scope, source) != "using" {
10964        return None;
10965    }
10966    let target = declarator.child_by_field_name("name")?;
10967    let mut components = Vec::new();
10968    append_cpp_name_components(target, source, &mut components)?;
10969    (components.len() >= 2).then_some((target, is_globally_qualified_cpp_name(target)))
10970}
10971
10972fn using_namespace_directive_name_node(node: Node<'_>) -> Option<Node<'_>> {
10973    let is_directive = node.kind() == "using_directive"
10974        || (node.kind() == "using_declaration"
10975            && (0..node.child_count()).any(|index| {
10976                node.child(index)
10977                    .is_some_and(|child| child.kind() == "namespace")
10978            }));
10979    if !is_directive {
10980        return None;
10981    }
10982    node.child_by_field_name("name")
10983        .or_else(|| node.named_child(node.named_child_count().checked_sub(1)?))
10984}
10985
10986fn using_named_scope(node: Node<'_>, source: &str) -> Option<Vec<String>> {
10987    let mut current = node.parent();
10988    while let Some(parent) = current {
10989        if matches!(
10990            parent.kind(),
10991            "compound_statement"
10992                | "function_definition"
10993                | "lambda_expression"
10994                | "for_statement"
10995                | "while_statement"
10996                | "if_statement"
10997                | "class_specifier"
10998                | "struct_specifier"
10999                | "union_specifier"
11000        ) {
11001            return None;
11002        }
11003        current = parent.parent();
11004    }
11005    Some(enclosing_namespace_components(node, source))
11006}
11007
11008fn ordinary_using_scope(node: Node<'_>) -> Option<(usize, usize, usize, bool)> {
11009    let mut current = node.parent();
11010    while let Some(scope) = current {
11011        if matches!(
11012            scope.kind(),
11013            "compound_statement"
11014                | "declaration_list"
11015                | "field_declaration_list"
11016                | "translation_unit"
11017        ) {
11018            let mut depth = 0;
11019            let mut ancestor = scope.parent();
11020            while let Some(parent) = ancestor {
11021                depth += 1;
11022                ancestor = parent.parent();
11023            }
11024            return Some((
11025                scope.start_byte(),
11026                scope.end_byte(),
11027                depth,
11028                scope.kind() == "compound_statement",
11029            ));
11030        }
11031        current = scope.parent();
11032    }
11033    None
11034}
11035
11036/// Build the per-file structured using index for `file`.
11037///
11038/// The result is a pure function of the file's parsed content, which is what
11039/// lets `CppSource::source_using_index` memoize it on the analyzer (#1927):
11040/// a `VisibilityIndex` is rebuilt per usage query, and rebuilding this index
11041/// per query re-walked a 9.5 MB amalgamation's AST for every candidate.
11042pub fn build_source_using_index(
11043    cpp: &dyn CppSource,
11044    token: QueryToken<'_>,
11045    file: &ProjectFile,
11046) -> SourceUsingIndex {
11047    let Some(prepared) = cpp.prepared_syntax(token, file) else {
11048        return SourceUsingIndex::default();
11049    };
11050    collect_source_using_index(cpp, file, prepared.tree().root_node(), prepared.source())
11051}
11052
11053fn collect_source_using_index(
11054    cpp: &dyn CppSource,
11055    source_file: &ProjectFile,
11056    root: Node<'_>,
11057    source: &str,
11058) -> SourceUsingIndex {
11059    #[cfg(not(any(test, feature = "test-support")))]
11060    let _ = cpp;
11061    let mut index = SourceUsingIndex::default();
11062    let orphaned_namespaces = collect_orphaned_namespace_envelopes(root, source);
11063    let mut stack = vec![root];
11064    while let Some(node) = stack.pop() {
11065        let target = match node.kind() {
11066            "using_directive" | "using_declaration" => {
11067                if let Some(namespace_node) = using_namespace_directive_name_node(node) {
11068                    let mut namespace_components = Vec::new();
11069                    append_cpp_name_components(namespace_node, source, &mut namespace_components)
11070                        .map(|_| EffectiveUsingTarget::Namespace {
11071                            namespace_components,
11072                            global: is_globally_qualified_cpp_name(namespace_node),
11073                        })
11074                } else if let Some(type_node) = ordinary_using_declaration_type_node(node) {
11075                    let mut target_components = Vec::new();
11076                    (append_cpp_name_components(type_node, source, &mut target_components)
11077                        .is_some()
11078                        && target_components.len() >= 2)
11079                        .then(|| EffectiveUsingTarget::Ordinary {
11080                            name: target_components
11081                                .last()
11082                                .expect("ordinary using has a terminal component")
11083                                .clone(),
11084                            target_components,
11085                            global: is_globally_qualified_cpp_name(type_node),
11086                        })
11087                } else {
11088                    None
11089                }
11090            }
11091            "declaration" => recovered_macro_using_declaration_type_node(node, source).and_then(
11092                |(type_node, global)| {
11093                    let mut target_components = Vec::new();
11094                    (append_cpp_name_components(type_node, source, &mut target_components)
11095                        .is_some()
11096                        && target_components.len() >= 2)
11097                        .then(|| EffectiveUsingTarget::Ordinary {
11098                            name: target_components
11099                                .last()
11100                                .expect("recovered ordinary using has a terminal component")
11101                                .clone(),
11102                            target_components,
11103                            global,
11104                        })
11105                },
11106            ),
11107            _ => None,
11108        };
11109        if let Some(target) = target {
11110            // Guard ancestry is one of the most expensive tree-sitter operations: Node::parent
11111            // searches from the root. The project index visits every AST node, but only these
11112            // structured using declarations need a guard environment. Keep the cheap target
11113            // classification ahead of both ancestor walks so non-using nodes remain a one-pass
11114            // walk and the total cost is O(nodes + using declarations * ancestor depth).
11115            #[cfg(any(test, feature = "test-support"))]
11116            cpp.record_using_guard_context_inspection_for_test();
11117            let required_guards = if callable_preprocessor_context_is_visible(node, source) {
11118                Some(HashSet::default())
11119            } else {
11120                preprocessor_guard_environment(node, source)
11121            };
11122            let Some(required_guards) = required_guards else {
11123                let mut cursor = node.walk();
11124                stack.extend(node.children(&mut cursor));
11125                continue;
11126            };
11127            if let Some((scope_start, scope_end, scope_depth, block_scope)) =
11128                ordinary_using_scope(node)
11129            {
11130                let declaration_namespace = enclosing_namespace_components(node, source);
11131                let declaration_namespace = if declaration_namespace.is_empty() {
11132                    recovered_orphaned_namespace_components(node, source, &orphaned_namespaces)
11133                        .unwrap_or(declaration_namespace)
11134                } else {
11135                    declaration_namespace
11136                };
11137                let namespace_scope = using_named_scope(node, source);
11138                let lexical_depth = declaration_namespace.len();
11139                let binding = OrdinaryTypeImport {
11140                    target,
11141                    source: source_file.clone(),
11142                    declaration_byte: node.end_byte(),
11143                    scope_start,
11144                    scope_end,
11145                    scope_depth,
11146                    block_scope,
11147                    lexical_depth,
11148                    declaration_namespace,
11149                    namespace_scope,
11150                    resolved_target_components: None,
11151                    required_guards,
11152                };
11153                match &binding.target {
11154                    EffectiveUsingTarget::Ordinary { name, .. } => index
11155                        .ordinary_by_name
11156                        .entry(name.clone())
11157                        .or_default()
11158                        .push(binding),
11159                    EffectiveUsingTarget::Namespace { .. } => index.directives.push(binding),
11160                }
11161            }
11162        }
11163        let mut cursor = node.walk();
11164        stack.extend(node.children(&mut cursor));
11165    }
11166    index
11167}
11168
11169struct OrphanedNamespaceEnvelope {
11170    body_end: usize,
11171    components: Vec<String>,
11172    class_names: HashSet<String>,
11173}
11174
11175/// Tree-sitter can terminate a namespace body at an object-like namespace
11176/// macro (for example `ABSL_NAMESPACE_BEGIN`), then parse the following
11177/// out-of-line definitions at translation-unit scope. A block-scoped using
11178/// declaration in one of those definitions still belongs to the namespace
11179/// selected by the malformed namespace envelope. Keep the envelope scan
11180/// source-local and reuse its structural ownership evidence for each using.
11181fn collect_orphaned_namespace_envelopes(
11182    root: Node<'_>,
11183    source: &str,
11184) -> Vec<OrphanedNamespaceEnvelope> {
11185    let mut envelopes = Vec::new();
11186    let mut stack = vec![root];
11187    while let Some(current) = stack.pop() {
11188        if current.kind() == "namespace_definition"
11189            && let Some(body) = current.child_by_field_name("body")
11190            && current.end_byte() == body.end_byte()
11191            && let Some(name) = current.child_by_field_name("name")
11192        {
11193            let mut components = enclosing_namespace_components(current, source);
11194            if append_cpp_name_components(name, source, &mut components).is_some()
11195                && !components.is_empty()
11196            {
11197                let mut class_names = HashSet::default();
11198                let mut body_stack = vec![body];
11199                while let Some(node) = body_stack.pop() {
11200                    if let Some(name) = orphaned_class_definition_name(node, source) {
11201                        class_names.insert(name);
11202                    }
11203                    let mut cursor = node.walk();
11204                    if node.kind() == "ERROR" {
11205                        body_stack.extend(node.children(&mut cursor));
11206                    } else {
11207                        body_stack.extend(node.named_children(&mut cursor));
11208                    }
11209                }
11210                envelopes.push(OrphanedNamespaceEnvelope {
11211                    body_end: body.end_byte(),
11212                    components,
11213                    class_names,
11214                });
11215            }
11216        }
11217        let mut cursor = current.walk();
11218        stack.extend(current.named_children(&mut cursor));
11219    }
11220    envelopes
11221}
11222
11223fn orphaned_class_definition_name(node: Node<'_>, source: &str) -> Option<String> {
11224    if matches!(
11225        node.kind(),
11226        "class_specifier" | "struct_specifier" | "union_specifier"
11227    ) {
11228        let body = node.child_by_field_name("body")?;
11229        let name = node.child_by_field_name("name")?;
11230        return (!name.is_missing() && !body.is_missing())
11231            .then(|| node_text(name, source).to_string());
11232    }
11233    if node.kind() != "ERROR" {
11234        return None;
11235    }
11236
11237    // When an object-like namespace macro is parsed as a function definition,
11238    // tree-sitter can place the entire class declaration inside an ERROR node
11239    // and leave the `class`/`struct` keyword as an anonymous child. Keep the
11240    // fallback structural: accept only a named class-like keyword followed by
11241    // a real body, never an arbitrary identifier mentioned in the envelope.
11242    for index in 0..node.child_count() {
11243        let Some(keyword) = node.child(index) else {
11244            continue;
11245        };
11246        if !matches!(keyword.kind(), "class" | "struct" | "union") {
11247            continue;
11248        }
11249        let mut name = None;
11250        for next_index in (index + 1)..node.child_count() {
11251            let Some(next) = node.child(next_index) else {
11252                continue;
11253            };
11254            if next.kind() == ";" {
11255                break;
11256            }
11257            if next.kind() == "{" {
11258                return name
11259                    .filter(|name_node: &Node<'_>| !name_node.is_missing())
11260                    .map(|name_node| node_text(name_node, source).to_string());
11261            }
11262            if name.is_none() && matches!(next.kind(), "identifier" | "type_identifier") {
11263                name = Some(next);
11264            }
11265        }
11266    }
11267    None
11268}
11269
11270fn recovered_orphaned_namespace_components(
11271    node: Node<'_>,
11272    source: &str,
11273    envelopes: &[OrphanedNamespaceEnvelope],
11274) -> Option<Vec<String>> {
11275    let owner_name = orphaned_using_owner_name(node, source)?;
11276    envelopes
11277        .iter()
11278        .filter(|envelope| {
11279            envelope.body_end <= node.start_byte() && envelope.class_names.contains(&owner_name)
11280        })
11281        .max_by_key(|envelope| envelope.body_end)
11282        .map(|envelope| envelope.components.clone())
11283}
11284
11285fn orphaned_using_owner_name(node: Node<'_>, source: &str) -> Option<String> {
11286    let function = std::iter::successors(node.parent(), |current| current.parent())
11287        .find(|current| current.kind() == "function_definition")?;
11288    let owner = function_definition_owner_lookup_node(function)?;
11289    let scope = owner.child_by_field_name("scope")?;
11290    let mut components = Vec::new();
11291    append_cpp_name_components(scope, source, &mut components)?;
11292    // A qualified out-of-line member definition already carries its namespace
11293    // in the declarator scope (for example `foo::Widget::run`). The recovery
11294    // path is only for parser-orphaned top-level members whose owner scope
11295    // collapsed to the bare class name; requiring that shape prevents an
11296    // earlier, unrelated namespace/class from leaking into a global function's
11297    // using-directive lookup.
11298    if components.len() != 1 {
11299        return None;
11300    }
11301    components.pop()
11302}
11303
11304fn build_project_using_index(visibility: &VisibilityIndex<'_>) -> ProjectUsingIndex {
11305    let started = Instant::now();
11306    let report_stats = std::env::var_os("BIFROST_CPP_VISIBILITY_STATS").is_some();
11307    let source_files = visibility.all_visible_source_files();
11308    if report_stats {
11309        eprintln!(
11310            "BIFROST_CPP_USING_INDEX_STATS status=started source_files={}",
11311            source_files.len()
11312        );
11313    }
11314    let mut project = ProjectUsingIndex::default();
11315    let mut ordinary_bindings = 0usize;
11316    for source_file in &source_files {
11317        // The per-file index is memoized on the analyzer, so assembling the
11318        // project index for a fresh `VisibilityIndex` copies bindings instead
11319        // of re-walking each file's AST (#1927).
11320        let source_index = visibility
11321            .cpp()
11322            .source_using_index(visibility.token(), source_file);
11323        for (name, bindings) in &source_index.ordinary_by_name {
11324            ordinary_bindings += bindings.len();
11325            project
11326                .ordinary_by_name
11327                .entry(name.clone())
11328                .or_default()
11329                .extend(bindings.iter().cloned());
11330        }
11331        project
11332            .directives
11333            .extend(source_index.directives.iter().cloned());
11334    }
11335    if report_stats {
11336        eprintln!(
11337            "BIFROST_CPP_USING_INDEX_STATS status=completed source_files={} ordinary_names={} ordinary_bindings={} directives={} elapsed_ms={}",
11338            source_files.len(),
11339            project.ordinary_by_name.len(),
11340            ordinary_bindings,
11341            project.directives.len(),
11342            started.elapsed().as_millis(),
11343        );
11344    }
11345    project
11346}
11347
11348fn project_using_index<'a>(visibility: &'a VisibilityIndex<'_>) -> &'a ProjectUsingIndex {
11349    visibility.project_using_index(|| build_project_using_index(visibility))
11350}
11351
11352/// Build the immutable project-wide using index before a parallel file scan.
11353///
11354/// Keeping the `OnceLock` publication here avoids making every scanner carry
11355/// an eager index, while callers that are about to fan out can prevent one
11356/// worker from doing the whole build as its peers wait on the lock.
11357pub fn prewarm_project_using_index(visibility: &VisibilityIndex<'_>) {
11358    let _ = project_using_index(visibility);
11359}
11360
11361fn effective_using_target_tiers(binding: &OrdinaryTypeImport) -> Vec<Vec<String>> {
11362    let (components, global) = match &binding.target {
11363        EffectiveUsingTarget::Ordinary {
11364            target_components,
11365            global,
11366            ..
11367        } => (target_components, *global),
11368        EffectiveUsingTarget::Namespace {
11369            namespace_components,
11370            global,
11371        } => (namespace_components, *global),
11372    };
11373    lexical_component_tiers(components, global, &binding.declaration_namespace).collect()
11374}
11375
11376fn using_binding_target_components_for_name(
11377    binding: &OrdinaryTypeImport,
11378    project: &ProjectUsingIndex,
11379    visibility: &VisibilityIndex<'_>,
11380    file: &ProjectFile,
11381    name: &str,
11382) -> Option<Vec<String>> {
11383    // Built once per call rather than per candidate: the filter runs over every
11384    // visible identifier of `name`, and the source is the same object each time.
11385    let cpp_source = CppGraphSource::from_source(visibility.cpp(), visibility.token());
11386    let visible_candidates = visibility
11387        .visible_identifier_candidates(file, name)
11388        .filter(|candidate| {
11389            candidate.is_class()
11390                || declared_type_alias(&cpp_source, candidate)
11391                || (candidate.is_function() && type_owner_of(&cpp_source, candidate).is_none())
11392        })
11393        .collect::<Vec<_>>();
11394    if visible_candidates.is_empty() {
11395        return None;
11396    }
11397    match &binding.target {
11398        EffectiveUsingTarget::Ordinary {
11399            name: imported_name,
11400            ..
11401        } if imported_name == name => {
11402            effective_using_target_tiers(binding)
11403                .into_iter()
11404                .find(|qualified| {
11405                    let qualified_name = qualified.join("::");
11406                    visible_candidates
11407                        .iter()
11408                        .any(|candidate| cpp_name_for(candidate) == qualified_name)
11409                })
11410        }
11411        EffectiveUsingTarget::Namespace { .. } => {
11412            visibility.note_using_namespace_lookup_for_test();
11413            let target_tiers = effective_using_target_tiers(binding);
11414            let resolved = target_tiers
11415                .iter()
11416                .find(|namespace_components| {
11417                    let namespace = namespace_components.join("::");
11418                    visible_candidates.iter().any(|candidate| {
11419                        visibility.note_using_name_candidate_inspection_for_test();
11420                        cpp_namespace_for(candidate).is_some_and(|candidate_namespace| {
11421                            candidate_namespace == namespace
11422                                || candidate_namespace.starts_with(&format!("{namespace}::"))
11423                        })
11424                    }) || project.directives.iter().any(|candidate| {
11425                        candidate.namespace_scope.as_deref()
11426                            == Some(namespace_components.as_slice())
11427                    }) || project
11428                        .ordinary_by_name
11429                        .values()
11430                        .flatten()
11431                        .any(|candidate| {
11432                            candidate.namespace_scope.as_deref()
11433                                == Some(namespace_components.as_slice())
11434                        })
11435                })
11436                .cloned();
11437            resolved.or_else(|| {
11438                // A sole lexical namespace tier is itself enough to retain the
11439                // directive. Candidate identity is resolved later, where
11440                // target guidance and macro-expanded owner names are available.
11441                // Dropping it here makes an unrelated same-terminal type hide
11442                // the actual namespace member before lookup can compare owners.
11443                (target_tiers.len() == 1)
11444                    .then(|| target_tiers.into_iter().next())
11445                    .flatten()
11446            })
11447        }
11448        EffectiveUsingTarget::Ordinary { .. } => None,
11449    }
11450}
11451
11452fn include_node_for_activation(root: Node<'_>, activation: usize) -> Option<Node<'_>> {
11453    let start = activation.checked_sub(1)?;
11454    let mut node = root.descendant_for_byte_range(start, activation)?;
11455    while node.kind() != "preproc_include" {
11456        node = node.parent()?;
11457    }
11458    Some(node)
11459}
11460
11461fn project_using_bindings(
11462    binding: OrdinaryTypeImport,
11463    visibility: &VisibilityIndex<'_>,
11464    file: &ProjectFile,
11465    root: Node<'_>,
11466    source: &str,
11467) -> Vec<OrdinaryTypeImport> {
11468    if binding.source == *file {
11469        return vec![binding];
11470    }
11471    if !visibility.source_is_visible(file, &binding.source) || binding.namespace_scope.is_none() {
11472        return Vec::new();
11473    }
11474    visibility.note_using_donor_activation_for_test();
11475    let Some(prepared) = visibility.cpp().prepared_syntax(visibility.token(), file) else {
11476        return Vec::new();
11477    };
11478    let projections = visibility
11479        .include_activation_for_source(visibility.cpp(), file, prepared.as_ref(), &binding.source)
11480        .map_or_else(
11481            || {
11482                visibility.conditional_include_projections_for_source(
11483                    file,
11484                    prepared.as_ref(),
11485                    &binding.source,
11486                )
11487            },
11488            |activation_byte| {
11489                Arc::from([ConditionalIncludeProjection {
11490                    activation_byte,
11491                    required_guards: HashSet::default(),
11492                    partial_guards: HashSet::default(),
11493                }])
11494            },
11495        );
11496    projections
11497        .iter()
11498        .cloned()
11499        .filter_map(|projection| {
11500            let required_guards =
11501                merge_preprocessor_guards(&binding.required_guards, &projection.required_guards)?;
11502            let mut projected = binding.clone();
11503            projected.required_guards = required_guards;
11504            project_using_binding_at_activation(projected, projection.activation_byte, root, source)
11505        })
11506        .collect()
11507}
11508
11509fn project_using_binding_at_activation(
11510    mut binding: OrdinaryTypeImport,
11511    activation: usize,
11512    root: Node<'_>,
11513    source: &str,
11514) -> Option<OrdinaryTypeImport> {
11515    let include = include_node_for_activation(root, activation)?;
11516    let include_namespace = enclosing_namespace_components(include, source);
11517    let mut declaration_namespace = include_namespace.clone();
11518    declaration_namespace.extend(binding.declaration_namespace);
11519    binding.declaration_namespace = declaration_namespace;
11520    binding.declaration_byte = activation;
11521    if let Some(prefix) = using_named_scope(include, source) {
11522        let mut projected = prefix;
11523        projected.extend(binding.namespace_scope.take().unwrap_or_default());
11524        binding.scope_depth = projected.len();
11525        binding.block_scope = false;
11526        binding.lexical_depth = projected.len();
11527        binding.namespace_scope = Some(projected);
11528        binding.scope_start = 0;
11529        binding.scope_end = usize::MAX;
11530        Some(binding)
11531    } else if let Some((start, end, depth, block_scope)) = ordinary_using_scope(include) {
11532        binding.namespace_scope = None;
11533        binding.scope_start = start;
11534        binding.scope_end = end;
11535        binding.scope_depth = depth;
11536        binding.block_scope = block_scope;
11537        binding.lexical_depth = include_namespace.len();
11538        Some(binding)
11539    } else {
11540        None
11541    }
11542}
11543
11544/// `node` may be any node of `file`'s tree; the projection reaches the tree
11545/// root itself when it needs one. `Node::parent` re-descends from the root on
11546/// every call (tree-sitter 0.24+), so climbing to the root eagerly at each
11547/// call site cost a near-full-AST scan per reference on a large flat file
11548/// (#1927); a name with no candidate bindings never pays for it.
11549pub fn effective_using_bindings_for_name(
11550    visibility: &VisibilityIndex<'_>,
11551    imports: &OrdinaryTypeImportCell,
11552    file: &ProjectFile,
11553    node: Node<'_>,
11554    source: &str,
11555    name: &str,
11556) -> Arc<[OrdinaryTypeImport]> {
11557    imports
11558        .projection_cell(name)
11559        .get_or_init(|| {
11560            let project = project_using_index(visibility);
11561            let name_bindings = project.ordinary_by_name.get(name);
11562            if name_bindings.is_none() && project.directives.is_empty() {
11563                return Arc::from(Vec::new());
11564            }
11565            let root = root_node(node);
11566            let mut projected = Vec::new();
11567            for binding in name_bindings
11568                .into_iter()
11569                .flatten()
11570                .chain(project.directives.iter())
11571            {
11572                if !visibility.source_is_visible(file, &binding.source) {
11573                    continue;
11574                }
11575                let target_components = using_binding_target_components_for_name(
11576                    binding, project, visibility, file, name,
11577                )
11578                .or_else(|| match &binding.target {
11579                    EffectiveUsingTarget::Ordinary {
11580                        name: imported_name,
11581                        target_components,
11582                        ..
11583                    } if imported_name == name => Some(target_components.clone()),
11584                    EffectiveUsingTarget::Ordinary { .. }
11585                    | EffectiveUsingTarget::Namespace { .. } => None,
11586                });
11587                let Some(target_components) = target_components else {
11588                    continue;
11589                };
11590                let mut binding = binding.clone();
11591                binding.resolved_target_components = Some(target_components);
11592                projected.extend(project_using_bindings(
11593                    binding, visibility, file, root, source,
11594                ));
11595            }
11596            Arc::from(projected)
11597        })
11598        .clone()
11599}
11600
11601pub fn initialized_ordinary_type_imports(
11602    root: Node<'_>,
11603    analyzer: &CppGraphSource<'_>,
11604    visibility: &VisibilityIndex<'_>,
11605    file: &ProjectFile,
11606    source: &str,
11607) -> OrdinaryTypeImportCell {
11608    let cell = visibility.ordinary_type_import_cell(file);
11609    let _ = (root, analyzer, source);
11610    cell
11611}
11612
11613/// `reference_guards` is the reference node's guard environment, computed once
11614/// by the caller and shared across every binding: recomputing it per binding
11615/// repeated a full ancestor climb whose every `Node::parent` step re-descends
11616/// from the root (#1927).
11617fn effective_using_binding_active(
11618    binding: &OrdinaryTypeImport,
11619    node: Node<'_>,
11620    lexical_scope: &[String],
11621    reference_guards: Option<&HashSet<PreprocessorGuard>>,
11622    visibility: &VisibilityIndex<'_>,
11623    file: &ProjectFile,
11624) -> bool {
11625    effective_using_binding_guards_active(
11626        binding,
11627        node.start_byte(),
11628        reference_guards,
11629        visibility,
11630        file,
11631    ) && binding.namespace_scope.as_ref().map_or_else(
11632        || binding.scope_start <= node.start_byte() && node.end_byte() <= binding.scope_end,
11633        |namespace| lexical_scope.starts_with(namespace),
11634    )
11635}
11636
11637fn effective_using_binding_guards_active(
11638    binding: &OrdinaryTypeImport,
11639    reference_byte: usize,
11640    reference_guards: Option<&HashSet<PreprocessorGuard>>,
11641    visibility: &VisibilityIndex<'_>,
11642    file: &ProjectFile,
11643) -> bool {
11644    binding.declaration_byte <= reference_byte
11645        && reference_guards.is_some_and(|active| binding.required_guards.is_subset(active))
11646        && effective_using_binding_guards_stable_between(binding, reference_byte, visibility, file)
11647}
11648
11649fn effective_using_binding_guards_compatible(
11650    binding: &OrdinaryTypeImport,
11651    reference_byte: usize,
11652    reference_guards: Option<&HashSet<PreprocessorGuard>>,
11653    visibility: &VisibilityIndex<'_>,
11654    file: &ProjectFile,
11655) -> bool {
11656    binding.source != *file
11657        && !binding.required_guards.is_empty()
11658        && binding.declaration_byte <= reference_byte
11659        && reference_guards.is_some_and(|active| {
11660            !binding.required_guards.is_subset(active)
11661                && merge_preprocessor_guards(&binding.required_guards, active).is_some()
11662        })
11663        && effective_using_binding_guards_stable_between(binding, reference_byte, visibility, file)
11664}
11665
11666fn effective_using_binding_guards_stable_between(
11667    binding: &OrdinaryTypeImport,
11668    reference_byte: usize,
11669    visibility: &VisibilityIndex<'_>,
11670    file: &ProjectFile,
11671) -> bool {
11672    visibility.preprocessor_guards_stable_between(
11673        file,
11674        binding.declaration_byte,
11675        reference_byte,
11676        &binding.required_guards,
11677    )
11678}
11679
11680#[allow(clippy::too_many_arguments)]
11681fn binding_type_candidates(
11682    binding: &OrdinaryTypeImport,
11683    active_bindings: &[&OrdinaryTypeImport],
11684    analyzer: &CppGraphSource<'_>,
11685    visibility: &VisibilityIndex<'_>,
11686    file: &ProjectFile,
11687    name: &str,
11688    direct_target: Option<&CodeUnit>,
11689    reference_byte: usize,
11690) -> Vec<(CodeUnit, Vec<String>)> {
11691    ordinary_binding_lookup_targets(binding, active_bindings, name)
11692        .into_iter()
11693        .flat_map(|target| {
11694            let mut candidates = visibility
11695                .visible_identifier_candidates(file, name)
11696                .filter(|candidate| {
11697                    (candidate.is_class() || declared_type_alias(analyzer, candidate))
11698                        && type_candidate_matches_lookup_components(
11699                            analyzer,
11700                            visibility,
11701                            file,
11702                            candidate,
11703                            reference_byte,
11704                            &target,
11705                        )
11706                })
11707                .cloned()
11708                .collect::<Vec<_>>();
11709            if candidates.is_empty()
11710                && matches!(binding.target, EffectiveUsingTarget::Namespace { .. })
11711                && let Some(target_unit) = direct_target
11712            {
11713                let expanded_target_name = macro_expanded_cpp_name_components(
11714                    visibility,
11715                    file,
11716                    target_unit,
11717                    reference_byte,
11718                );
11719                if (target_unit.is_class() || declared_type_alias(analyzer, target_unit))
11720                    && expanded_target_name == target
11721                    && visibility.external_type_candidate_visible_at(
11722                        file,
11723                        target_unit,
11724                        reference_byte,
11725                    )
11726                {
11727                    candidates.push(target_unit.clone());
11728                }
11729            }
11730            if candidates.is_empty()
11731                && matches!(binding.target, EffectiveUsingTarget::Namespace { .. })
11732                && let Some(target_unit) = direct_target
11733            {
11734                let visible_types = visibility
11735                    .visible_identifier_candidates(file, name)
11736                    .filter(|candidate| {
11737                        candidate.is_class() || declared_type_alias(analyzer, candidate)
11738                    })
11739                    .collect::<Vec<_>>();
11740                let uniquely_names_target = !visible_types.is_empty()
11741                    && visible_types
11742                        .iter()
11743                        .all(|candidate| same_visible_symbol(candidate, target_unit));
11744                if uniquely_names_target {
11745                    candidates.extend(visible_types.into_iter().cloned());
11746                }
11747            }
11748            candidates
11749                .into_iter()
11750                .map(move |candidate| (candidate, target.clone()))
11751        })
11752        .collect()
11753}
11754
11755fn macro_expanded_cpp_name_components(
11756    visibility: &VisibilityIndex<'_>,
11757    file: &ProjectFile,
11758    unit: &CodeUnit,
11759    reference_byte: usize,
11760) -> Vec<String> {
11761    brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
11762        brokk_bifrost_core::analyzer::Language::Cpp,
11763        &cpp_name_for(unit),
11764    )
11765    .into_iter()
11766    .flat_map(|component| {
11767        macro_expanded_cpp_name_component(visibility, file, component, reference_byte)
11768    })
11769    .collect()
11770}
11771
11772fn macro_expanded_cpp_name_component(
11773    visibility: &VisibilityIndex<'_>,
11774    file: &ProjectFile,
11775    component: String,
11776    reference_byte: usize,
11777) -> Vec<String> {
11778    let Some(replacement) =
11779        visibility.object_macro_replacement_at(file, &component, reference_byte)
11780    else {
11781        return vec![component];
11782    };
11783    let expanded = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
11784        brokk_bifrost_core::analyzer::Language::Cpp,
11785        &replacement,
11786    );
11787    if expanded.is_empty() {
11788        vec![component]
11789    } else {
11790        expanded
11791    }
11792}
11793
11794/// Whether a visible type has the requested qualified spelling.
11795///
11796/// Members of an inline namespace are also members of its enclosing namespace,
11797/// so an ordinary using-declaration may legally omit the inline component. The
11798/// stored FQ name retains that component to keep declarations distinct. Recover
11799/// the omitted spellings from the candidate declaration's namespace ancestors,
11800/// using CST `inline` tokens rather than guessing from names.
11801fn type_candidate_matches_lookup_components(
11802    analyzer: &CppGraphSource<'_>,
11803    visibility: &VisibilityIndex<'_>,
11804    file: &ProjectFile,
11805    candidate: &CodeUnit,
11806    reference_byte: usize,
11807    target: &[String],
11808) -> bool {
11809    let expanded = macro_expanded_cpp_name_components(visibility, file, candidate, reference_byte);
11810    if expanded == target {
11811        return true;
11812    }
11813    let Some(cpp) = analyzer.cpp else {
11814        return false;
11815    };
11816    let Some(prepared) = cpp.prepared_syntax(visibility.token(), candidate.source()) else {
11817        return false;
11818    };
11819    let root = prepared.tree().root_node();
11820    for range in analyzer.ranges(candidate) {
11821        let Some(mut current) = root.descendant_for_byte_range(range.start_byte, range.end_byte)
11822        else {
11823            continue;
11824        };
11825        let mut namespaces = Vec::<(Vec<String>, bool)>::new();
11826        loop {
11827            if current.kind() == "namespace_definition"
11828                && let Some(name) = current.child_by_field_name("name")
11829            {
11830                let mut components = Vec::new();
11831                if append_cpp_name_components(name, prepared.source(), &mut components).is_some()
11832                    && !components.is_empty()
11833                {
11834                    let inline = (0..current.child_count())
11835                        .filter_map(|index| current.child(index))
11836                        .any(|child| !child.is_named() && child.kind() == "inline");
11837                    namespaces.push((components, inline));
11838                }
11839            }
11840            let Some(parent) = current.parent() else {
11841                break;
11842            };
11843            current = parent;
11844        }
11845        namespaces.reverse();
11846        let mut namespace_components = Vec::new();
11847        let mut inline_indexes = HashSet::default();
11848        for (components, inline) in namespaces {
11849            for component in components {
11850                let expanded_component =
11851                    macro_expanded_cpp_name_component(visibility, file, component, reference_byte);
11852                if inline {
11853                    inline_indexes.extend(
11854                        namespace_components.len()
11855                            ..namespace_components.len() + expanded_component.len(),
11856                    );
11857                }
11858                namespace_components.extend(expanded_component);
11859            }
11860        }
11861        if inline_indexes.is_empty() || !expanded.starts_with(&namespace_components) {
11862            continue;
11863        }
11864        // Each inline namespace component can be present or elided. Compare
11865        // those alternatives as a small dynamic program instead of generating
11866        // every subset of a deeply nested inline-namespace chain.
11867        let mut reachable = vec![false; target.len() + 1];
11868        reachable[0] = true;
11869        for (index, component) in expanded.iter().enumerate() {
11870            let mut next = vec![false; target.len() + 1];
11871            for (target_index, reached) in reachable.iter().copied().enumerate() {
11872                if !reached {
11873                    continue;
11874                }
11875                if inline_indexes.contains(&index) {
11876                    next[target_index] = true;
11877                }
11878                if target
11879                    .get(target_index)
11880                    .is_some_and(|target_component| target_component == component)
11881                {
11882                    next[target_index + 1] = true;
11883                }
11884            }
11885            reachable = next;
11886        }
11887        if reachable[target.len()] {
11888            return true;
11889        }
11890    }
11891    false
11892}
11893
11894#[allow(clippy::too_many_arguments)]
11895fn resolved_type_import(
11896    candidates: Vec<(CodeUnit, Vec<String>)>,
11897    lexical_depth: usize,
11898    is_direct: bool,
11899    analyzer: &CppGraphSource<'_>,
11900    visibility: &VisibilityIndex<'_>,
11901    file: &ProjectFile,
11902    direct_target: Option<&CodeUnit>,
11903) -> OrdinaryTypeImportResolution {
11904    let logical = deduplicate_type_import_candidates(candidates);
11905    let selected = match logical.as_slice() {
11906        [] => return OrdinaryTypeImportResolution::Missing,
11907        [only] => only,
11908        // Several declarations of one FQN in one file are configuration
11909        // spellings of one entity, not competing types (#1845): the imported
11910        // name is unambiguous, only the branch that supplies it depends on the
11911        // build.
11912        several => {
11913            let units = several
11914                .iter()
11915                .map(|(unit, _)| unit)
11916                .collect::<Vec<&CodeUnit>>();
11917            let Some(spelling) = direct_target.and_then(|target| {
11918                visibility.same_fqn_type_spelling_for_target(analyzer, file, &units, target)
11919            }) else {
11920                return OrdinaryTypeImportResolution::Ambiguous { lexical_depth };
11921            };
11922            several
11923                .iter()
11924                .find(|(unit, _)| same_symbol(unit, spelling))
11925                .expect("the selected spelling is one of the imported candidates")
11926        }
11927    };
11928    OrdinaryTypeImportResolution::Resolved {
11929        target: selected.0.clone(),
11930        target_components: selected.1.clone(),
11931        lexical_depth,
11932        is_direct,
11933    }
11934}
11935
11936#[allow(clippy::too_many_arguments)]
11937fn ordinary_type_import_resolution(
11938    node: Node<'_>,
11939    components: &[String],
11940    global: bool,
11941    analyzer: &CppGraphSource<'_>,
11942    visibility: &VisibilityIndex<'_>,
11943    imports: &OrdinaryTypeImportCell,
11944    file: &ProjectFile,
11945    source: &str,
11946    lexical_scope: &[String],
11947    direct_target: Option<&CodeUnit>,
11948) -> OrdinaryTypeImportResolution {
11949    if global || components.len() != 1 {
11950        return OrdinaryTypeImportResolution::Missing;
11951    }
11952    let name = &components[0];
11953    let bindings = effective_using_bindings_for_name(visibility, imports, file, node, source, name);
11954    // Guard ancestry climbs the whole ancestor chain, and each `Node::parent`
11955    // step re-descends from the root (#1927). A name with no bindings needs
11956    // none of it, and one environment serves every binding of the reference.
11957    if bindings.is_empty() {
11958        return OrdinaryTypeImportResolution::Missing;
11959    }
11960    let reference_guards = preprocessor_guard_environment(node, source);
11961    let active = bindings
11962        .iter()
11963        .filter(|binding| {
11964            effective_using_binding_active(
11965                binding,
11966                node,
11967                lexical_scope,
11968                reference_guards.as_ref(),
11969                visibility,
11970                file,
11971            )
11972        })
11973        .collect::<Vec<_>>();
11974    let transitive = bindings
11975        .iter()
11976        .filter(|binding| {
11977            effective_using_binding_guards_active(
11978                binding,
11979                node.start_byte(),
11980                reference_guards.as_ref(),
11981                visibility,
11982                file,
11983            ) && (binding.namespace_scope.is_some()
11984                || (binding.scope_start <= node.start_byte()
11985                    && node.end_byte() <= binding.scope_end))
11986        })
11987        .collect::<Vec<_>>();
11988    ordinary_type_import_resolution_for_bindings(
11989        node,
11990        name,
11991        analyzer,
11992        visibility,
11993        file,
11994        lexical_scope,
11995        direct_target,
11996        &active,
11997        &transitive,
11998    )
11999}
12000
12001#[allow(clippy::too_many_arguments)]
12002fn compatible_foreign_type_import_resolution(
12003    node: Node<'_>,
12004    components: &[String],
12005    global: bool,
12006    analyzer: &CppGraphSource<'_>,
12007    visibility: &VisibilityIndex<'_>,
12008    imports: &OrdinaryTypeImportCell,
12009    file: &ProjectFile,
12010    source: &str,
12011    lexical_scope: &[String],
12012    direct_target: Option<&CodeUnit>,
12013) -> OrdinaryTypeImportResolution {
12014    if global || components.len() != 1 {
12015        return OrdinaryTypeImportResolution::Missing;
12016    }
12017    let name = &components[0];
12018    let bindings = effective_using_bindings_for_name(visibility, imports, file, node, source, name);
12019    if bindings.is_empty() {
12020        return OrdinaryTypeImportResolution::Missing;
12021    }
12022    let reference_guards = preprocessor_guard_environment(node, source);
12023    let compatible = bindings
12024        .iter()
12025        .filter(|binding| {
12026            effective_using_binding_guards_compatible(
12027                binding,
12028                node.start_byte(),
12029                reference_guards.as_ref(),
12030                visibility,
12031                file,
12032            ) && binding.namespace_scope.as_ref().map_or_else(
12033                || binding.scope_start <= node.start_byte() && node.end_byte() <= binding.scope_end,
12034                |namespace| lexical_scope.starts_with(namespace),
12035            )
12036        })
12037        .collect::<Vec<_>>();
12038    let transitive = bindings
12039        .iter()
12040        .filter(|binding| {
12041            effective_using_binding_guards_compatible(
12042                binding,
12043                node.start_byte(),
12044                reference_guards.as_ref(),
12045                visibility,
12046                file,
12047            ) && (binding.namespace_scope.is_some()
12048                || (binding.scope_start <= node.start_byte()
12049                    && node.end_byte() <= binding.scope_end))
12050        })
12051        .collect::<Vec<_>>();
12052    ordinary_type_import_resolution_for_bindings(
12053        node,
12054        name,
12055        analyzer,
12056        visibility,
12057        file,
12058        lexical_scope,
12059        direct_target,
12060        &compatible,
12061        &transitive,
12062    )
12063}
12064
12065#[allow(clippy::too_many_arguments)]
12066fn ordinary_type_import_resolution_for_bindings(
12067    node: Node<'_>,
12068    name: &str,
12069    analyzer: &CppGraphSource<'_>,
12070    visibility: &VisibilityIndex<'_>,
12071    file: &ProjectFile,
12072    lexical_scope: &[String],
12073    direct_target: Option<&CodeUnit>,
12074    active: &[&OrdinaryTypeImport],
12075    transitive: &[&OrdinaryTypeImport],
12076) -> OrdinaryTypeImportResolution {
12077    let mut concrete_depths = active
12078        .iter()
12079        .filter(|binding| binding.namespace_scope.is_none())
12080        .map(|binding| binding.scope_depth)
12081        .collect::<Vec<_>>();
12082    concrete_depths.sort_unstable();
12083    concrete_depths.dedup();
12084    for depth in concrete_depths.into_iter().rev() {
12085        let at_tier = active
12086            .iter()
12087            .copied()
12088            .filter(|binding| binding.namespace_scope.is_none() && binding.scope_depth == depth);
12089        let direct = at_tier
12090            .clone()
12091            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
12092            .flat_map(|binding| {
12093                binding_type_candidates(
12094                    binding,
12095                    transitive,
12096                    analyzer,
12097                    visibility,
12098                    file,
12099                    name,
12100                    direct_target,
12101                    node.start_byte(),
12102                )
12103            })
12104            .collect::<Vec<_>>();
12105        if !direct.is_empty() {
12106            return resolved_type_import(
12107                direct,
12108                lexical_scope.len(),
12109                true,
12110                analyzer,
12111                visibility,
12112                file,
12113                direct_target,
12114            );
12115        }
12116        let directives = at_tier
12117            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
12118            .flat_map(|binding| {
12119                binding_type_candidates(
12120                    binding,
12121                    transitive,
12122                    analyzer,
12123                    visibility,
12124                    file,
12125                    name,
12126                    direct_target,
12127                    node.start_byte(),
12128                )
12129            })
12130            .collect::<Vec<_>>();
12131        if !directives.is_empty() {
12132            return resolved_type_import(
12133                directives,
12134                lexical_scope.len(),
12135                false,
12136                analyzer,
12137                visibility,
12138                file,
12139                direct_target,
12140            );
12141        }
12142    }
12143    for prefix_len in (0..=lexical_scope.len()).rev() {
12144        let tier = &lexical_scope[..prefix_len];
12145        let at_tier = active
12146            .iter()
12147            .copied()
12148            .filter(|binding| binding.namespace_scope.as_deref() == Some(tier));
12149        let direct = at_tier
12150            .clone()
12151            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
12152            .flat_map(|binding| {
12153                binding_type_candidates(
12154                    binding,
12155                    transitive,
12156                    analyzer,
12157                    visibility,
12158                    file,
12159                    name,
12160                    direct_target,
12161                    node.start_byte(),
12162                )
12163            })
12164            .collect::<Vec<_>>();
12165        if !direct.is_empty() {
12166            return resolved_type_import(
12167                direct,
12168                prefix_len,
12169                true,
12170                analyzer,
12171                visibility,
12172                file,
12173                direct_target,
12174            );
12175        }
12176        let directives = at_tier
12177            .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
12178            .flat_map(|binding| {
12179                binding_type_candidates(
12180                    binding,
12181                    transitive,
12182                    analyzer,
12183                    visibility,
12184                    file,
12185                    name,
12186                    direct_target,
12187                    node.start_byte(),
12188                )
12189            })
12190            .collect::<Vec<_>>();
12191        if !directives.is_empty() {
12192            return resolved_type_import(
12193                directives,
12194                prefix_len,
12195                false,
12196                analyzer,
12197                visibility,
12198                file,
12199                direct_target,
12200            );
12201        }
12202    }
12203    OrdinaryTypeImportResolution::Missing
12204}
12205
12206#[allow(clippy::too_many_arguments)]
12207pub fn resolve_type_components_lexically_at(
12208    node: Node<'_>,
12209    components: &[String],
12210    global: bool,
12211    analyzer: &CppGraphSource<'_>,
12212    visibility: &VisibilityIndex<'_>,
12213    ordinary_type_imports: &OrdinaryTypeImportCell,
12214    file: &ProjectFile,
12215    source: &str,
12216) -> LexicalTypeResolution {
12217    resolve_type_components_lexically_at_inner(
12218        node,
12219        components,
12220        global,
12221        analyzer,
12222        visibility,
12223        ordinary_type_imports,
12224        file,
12225        source,
12226        None,
12227        false,
12228        false,
12229        false,
12230        None,
12231    )
12232}
12233
12234/// Resolve a type at its lexical reference site while retaining the identity
12235/// of an alias that C++ lookup selects.
12236///
12237/// Forward navigation uses the selected spelling as its destination, whereas
12238/// graph attribution normally canonicalizes an alias to its target. Both
12239/// surfaces must still apply the same ordinary using-declarations, declaration
12240/// order, guard state, and lexical-depth precedence.
12241#[allow(clippy::too_many_arguments)]
12242pub fn resolve_type_components_lexically_at_preserving_alias(
12243    node: Node<'_>,
12244    components: &[String],
12245    global: bool,
12246    analyzer: &CppGraphSource<'_>,
12247    visibility: &VisibilityIndex<'_>,
12248    file: &ProjectFile,
12249    source: &str,
12250) -> LexicalTypeResolution {
12251    let ordinary_type_imports =
12252        initialized_ordinary_type_imports(root_node(node), analyzer, visibility, file, source);
12253    resolve_type_components_lexically_at_inner(
12254        node,
12255        components,
12256        global,
12257        analyzer,
12258        visibility,
12259        &ordinary_type_imports,
12260        file,
12261        source,
12262        None,
12263        false,
12264        true,
12265        true,
12266        None,
12267    )
12268}
12269
12270#[allow(clippy::too_many_arguments)]
12271fn resolve_type_components_lexically_at_preserving_alias_with_scope_cache(
12272    node: Node<'_>,
12273    components: &[String],
12274    global: bool,
12275    analyzer: &CppGraphSource<'_>,
12276    visibility: &VisibilityIndex<'_>,
12277    ordinary_type_imports: &OrdinaryTypeImportCell,
12278    file: &ProjectFile,
12279    source: &str,
12280    scope_cache: Option<&LexicalScopeCache>,
12281) -> LexicalTypeResolution {
12282    resolve_type_components_lexically_at_inner(
12283        node,
12284        components,
12285        global,
12286        analyzer,
12287        visibility,
12288        ordinary_type_imports,
12289        file,
12290        source,
12291        None,
12292        false,
12293        true,
12294        false,
12295        scope_cache,
12296    )
12297}
12298
12299#[allow(clippy::too_many_arguments)]
12300fn resolve_type_components_lexically_at_for_target_with_scope_cache(
12301    node: Node<'_>,
12302    components: &[String],
12303    global: bool,
12304    analyzer: &CppGraphSource<'_>,
12305    visibility: &VisibilityIndex<'_>,
12306    ordinary_type_imports: &OrdinaryTypeImportCell,
12307    file: &ProjectFile,
12308    source: &str,
12309    target: &CodeUnit,
12310    apply_structured_prefilter: bool,
12311    scope_cache: Option<&LexicalScopeCache>,
12312) -> LexicalTypeResolution {
12313    resolve_type_components_lexically_at_inner(
12314        node,
12315        components,
12316        global,
12317        analyzer,
12318        visibility,
12319        ordinary_type_imports,
12320        file,
12321        source,
12322        Some(target),
12323        apply_structured_prefilter,
12324        false,
12325        false,
12326        scope_cache,
12327    )
12328}
12329
12330#[allow(clippy::too_many_arguments)]
12331fn resolve_type_components_lexically_at_preserving_alias_with_recovered_scope(
12332    node: Node<'_>,
12333    components: &[String],
12334    global: bool,
12335    analyzer: &CppGraphSource<'_>,
12336    visibility: &VisibilityIndex<'_>,
12337    ordinary_type_imports: &OrdinaryTypeImportCell,
12338    file: &ProjectFile,
12339    source: &str,
12340    recovered_scope: &[String],
12341) -> LexicalTypeResolution {
12342    resolve_type_components_in_authoritative_scope(
12343        node,
12344        components,
12345        global,
12346        analyzer,
12347        visibility,
12348        ordinary_type_imports,
12349        file,
12350        source,
12351        None,
12352        false,
12353        true,
12354        false,
12355        recovered_scope.to_vec(),
12356    )
12357}
12358
12359#[allow(clippy::too_many_arguments)]
12360fn resolve_type_components_lexically_at_for_target_with_recovered_scope(
12361    node: Node<'_>,
12362    components: &[String],
12363    global: bool,
12364    analyzer: &CppGraphSource<'_>,
12365    visibility: &VisibilityIndex<'_>,
12366    ordinary_type_imports: &OrdinaryTypeImportCell,
12367    file: &ProjectFile,
12368    source: &str,
12369    target: &CodeUnit,
12370    apply_structured_prefilter: bool,
12371    recovered_scope: &[String],
12372) -> LexicalTypeResolution {
12373    resolve_type_components_in_authoritative_scope(
12374        node,
12375        components,
12376        global,
12377        analyzer,
12378        visibility,
12379        ordinary_type_imports,
12380        file,
12381        source,
12382        Some(target),
12383        apply_structured_prefilter,
12384        false,
12385        false,
12386        recovered_scope.to_vec(),
12387    )
12388}
12389
12390#[allow(clippy::too_many_arguments)]
12391fn resolve_type_components_lexically_at_inner(
12392    node: Node<'_>,
12393    components: &[String],
12394    global: bool,
12395    analyzer: &CppGraphSource<'_>,
12396    visibility: &VisibilityIndex<'_>,
12397    ordinary_type_imports: &OrdinaryTypeImportCell,
12398    file: &ProjectFile,
12399    source: &str,
12400    direct_target: Option<&CodeUnit>,
12401    apply_structured_prefilter: bool,
12402    preserve_alias: bool,
12403    allow_compatible_foreign_import: bool,
12404    scope_cache: Option<&LexicalScopeCache>,
12405) -> LexicalTypeResolution {
12406    let report_stats = std::env::var_os("BIFROST_CPP_VISIBILITY_STATS").is_some();
12407    let lexical_scope_started = Instant::now();
12408    if report_stats {
12409        eprintln!("BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=started");
12410    }
12411    let lexical_scope = if global {
12412        Vec::new()
12413    } else {
12414        match cached_enclosing_lexical_scope_components_with_unresolved_owner(
12415            node,
12416            analyzer,
12417            visibility,
12418            file,
12419            source,
12420            true,
12421            recovered_macro_decorated_declarator_type(node)
12422                == Some(RecoveredDeclaratorTypeContext::FunctionDefinition),
12423            scope_cache,
12424        ) {
12425            LexicalScopeResolution::Resolved(scope) => scope,
12426            LexicalScopeResolution::Ambiguous => {
12427                if report_stats {
12428                    eprintln!(
12429                        "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=completed outcome=ambiguous elapsed_ms={}",
12430                        lexical_scope_started.elapsed().as_millis(),
12431                    );
12432                }
12433                return LexicalTypeResolution::Ambiguous;
12434            }
12435            LexicalScopeResolution::Missing => {
12436                if report_stats {
12437                    eprintln!(
12438                        "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=completed outcome=missing elapsed_ms={}",
12439                        lexical_scope_started.elapsed().as_millis(),
12440                    );
12441                }
12442                return LexicalTypeResolution::Missing;
12443            }
12444        }
12445    };
12446    if report_stats {
12447        eprintln!(
12448            "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=completed components={} elapsed_ms={}",
12449            lexical_scope.len(),
12450            lexical_scope_started.elapsed().as_millis(),
12451        );
12452    }
12453    resolve_type_components_lexically_at_scoped(
12454        node,
12455        components,
12456        global,
12457        analyzer,
12458        visibility,
12459        ordinary_type_imports,
12460        file,
12461        source,
12462        direct_target,
12463        apply_structured_prefilter,
12464        preserve_alias,
12465        allow_compatible_foreign_import,
12466        lexical_scope,
12467    )
12468}
12469
12470#[allow(clippy::too_many_arguments)]
12471fn resolve_type_components_lexically_at_scoped(
12472    node: Node<'_>,
12473    components: &[String],
12474    global: bool,
12475    analyzer: &CppGraphSource<'_>,
12476    visibility: &VisibilityIndex<'_>,
12477    ordinary_type_imports: &OrdinaryTypeImportCell,
12478    file: &ProjectFile,
12479    source: &str,
12480    direct_target: Option<&CodeUnit>,
12481    apply_structured_prefilter: bool,
12482    preserve_alias: bool,
12483    allow_compatible_foreign_import: bool,
12484    mut lexical_scope: Vec<String>,
12485) -> LexicalTypeResolution {
12486    if !global
12487        && components.len() == 1
12488        // The two constant-time conditions run before the ancestor climb: each
12489        // `Node::parent` step re-descends from the root (#1927).
12490        && let Some(target) = direct_target
12491        && lexical_scope
12492            .last()
12493            .is_none_or(|last| last != &components[0])
12494        // A recovered class may contain a real member function nested inside
12495        // the malformed outer wrapper (for example tinyxml2's macro-prefixed
12496        // XMLConstHandle). The nearest function_definition is then the member
12497        // itself, so inspect the complete ancestor chain.
12498        && has_malformed_wrapper_function_definition_ancestor(node)
12499        && let Some(indexed_namespace) =
12500            visibility.target_preserving_reference_namespace(analyzer, file, &components[0], target)
12501        && (lexical_scope.is_empty() || !lexical_scope.starts_with(&indexed_namespace))
12502    {
12503        lexical_scope = indexed_namespace;
12504    }
12505    resolve_type_components_in_authoritative_scope(
12506        node,
12507        components,
12508        global,
12509        analyzer,
12510        visibility,
12511        ordinary_type_imports,
12512        file,
12513        source,
12514        direct_target,
12515        apply_structured_prefilter,
12516        preserve_alias,
12517        allow_compatible_foreign_import,
12518        lexical_scope,
12519    )
12520}
12521
12522/// Resolve within a scope already proven by recovered syntax.
12523///
12524/// Unlike parser-derived scope, this scope must not be replaced with the
12525/// queried target's namespace: doing so would let target guidance override a
12526/// nearer declaration represented by the recovered syntax.
12527#[allow(clippy::too_many_arguments)]
12528fn resolve_type_components_in_authoritative_scope(
12529    node: Node<'_>,
12530    components: &[String],
12531    global: bool,
12532    analyzer: &CppGraphSource<'_>,
12533    visibility: &VisibilityIndex<'_>,
12534    ordinary_type_imports: &OrdinaryTypeImportCell,
12535    file: &ProjectFile,
12536    source: &str,
12537    direct_target: Option<&CodeUnit>,
12538    apply_structured_prefilter: bool,
12539    preserve_alias: bool,
12540    allow_compatible_foreign_import: bool,
12541    lexical_scope: Vec<String>,
12542) -> LexicalTypeResolution {
12543    if apply_structured_prefilter
12544        && direct_target.is_some()
12545        && !preserve_alias
12546        && !global
12547        && components.len() == 1
12548        && !visibility.coarse_unqualified_type_reference_may_resolve(file, &components[0])
12549    {
12550        return LexicalTypeResolution::Missing;
12551    }
12552    // A recovered macro-prefixed return type can share its global spelling
12553    // with aliases from mutually exclusive included headers. C++ lookup uses
12554    // the declaration physically present earlier in this file; the visibility
12555    // index deliberately retains every configuration alternative. Restore
12556    // that precedence only for the exact recovered scope and lexical tier.
12557    if !global
12558        && components.len() == 1
12559        && recovered_macro_decorated_type_node(node).is_some()
12560        && let Some(resolution) = recovered_same_file_type_alias_resolution(
12561            node,
12562            components,
12563            analyzer,
12564            visibility,
12565            file,
12566            direct_target,
12567            &lexical_scope,
12568        )
12569    {
12570        return resolution;
12571    }
12572    if apply_structured_prefilter
12573        && let Some(target) = direct_target
12574        && !preserve_alias
12575        && !visibility.structured_type_reference_may_resolve_to_target(
12576            analyzer,
12577            file,
12578            components,
12579            global,
12580            &lexical_scope,
12581            target,
12582        )
12583    {
12584        return LexicalTypeResolution::Missing;
12585    }
12586    let report_stats = std::env::var_os("BIFROST_CPP_VISIBILITY_STATS").is_some();
12587    let lexical_normal_started = Instant::now();
12588    if report_stats {
12589        eprintln!("BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_normal status=started");
12590    }
12591    let normal = if preserve_alias {
12592        visibility.resolve_type_components_lexically_for_forward(
12593            analyzer,
12594            file,
12595            components,
12596            global,
12597            &lexical_scope,
12598        )
12599    } else {
12600        direct_target.map_or_else(
12601            || {
12602                visibility.resolve_type_components_lexically(
12603                    analyzer,
12604                    file,
12605                    components,
12606                    global,
12607                    &lexical_scope,
12608                )
12609            },
12610            |target| {
12611                visibility.resolve_type_components_lexically_for_target(
12612                    analyzer,
12613                    file,
12614                    components,
12615                    global,
12616                    &lexical_scope,
12617                    target,
12618                )
12619            },
12620        )
12621    };
12622    if report_stats {
12623        eprintln!(
12624            "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_normal status=completed elapsed_ms={}",
12625            lexical_normal_started.elapsed().as_millis(),
12626        );
12627    }
12628    let normal = match normal {
12629        LexicalTypeResolution::Resolved { ref unit, .. }
12630            if !visibility
12631                .external_type_candidate_visible_in_context(analyzer, file, unit, node)
12632                && !direct_target.is_some_and(|target| {
12633                    let candidate_refs = visibility
12634                        .visible_identifier_candidates(file, target.identifier())
12635                        .collect::<Vec<_>>();
12636                    visibility.c_tag_declaration_family_matches_target(
12637                        analyzer,
12638                        file,
12639                        &candidate_refs,
12640                        target,
12641                    )
12642                }) =>
12643        {
12644            LexicalTypeResolution::Missing
12645        }
12646        resolution => resolution,
12647    };
12648    let normal_depth = match &normal {
12649        LexicalTypeResolution::Resolved { components, .. } => {
12650            Some(components.len().saturating_sub(1))
12651        }
12652        LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
12653    };
12654    // Ordinary using-declarations participate in unqualified lookup at their
12655    // lexical scope. They therefore replace the resolver's terminal/global
12656    // fallback at the same or a shallower depth. A declaration in a more deeply
12657    // nested named scope is the closer lexical result and remains authoritative.
12658    // Ambiguous imports fail closed unless such a closer declaration exists.
12659    let ordinary_import_started = Instant::now();
12660    if report_stats {
12661        eprintln!("BIFROST_CPP_TYPE_LEXICAL_PHASE phase=ordinary_import status=started");
12662    }
12663    let ordinary_import_resolution = ordinary_type_import_resolution(
12664        node,
12665        components,
12666        global,
12667        analyzer,
12668        visibility,
12669        ordinary_type_imports,
12670        file,
12671        source,
12672        &lexical_scope,
12673        direct_target,
12674    );
12675    if report_stats {
12676        eprintln!(
12677            "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=ordinary_import status=completed elapsed_ms={}",
12678            ordinary_import_started.elapsed().as_millis(),
12679        );
12680    }
12681    let resolution = match ordinary_import_resolution {
12682        OrdinaryTypeImportResolution::Missing => normal,
12683        OrdinaryTypeImportResolution::Resolved {
12684            lexical_depth,
12685            is_direct,
12686            ..
12687        } if matches!(&normal, LexicalTypeResolution::Ambiguous)
12688            || normal_depth.is_some_and(|depth| {
12689                depth > lexical_depth || (!is_direct && depth == lexical_depth)
12690            }) =>
12691        {
12692            normal
12693        }
12694        OrdinaryTypeImportResolution::Resolved {
12695            target,
12696            target_components,
12697            ..
12698        } => visibility.resolve_imported_type_candidate(
12699            analyzer,
12700            file,
12701            &target,
12702            &target_components,
12703            direct_target,
12704            preserve_alias,
12705        ),
12706        OrdinaryTypeImportResolution::Ambiguous { lexical_depth }
12707            if normal_depth.is_some_and(|depth| depth > lexical_depth) =>
12708        {
12709            normal
12710        }
12711        OrdinaryTypeImportResolution::Ambiguous { .. } => LexicalTypeResolution::Ambiguous,
12712    };
12713    if !allow_compatible_foreign_import || !matches!(resolution, LexicalTypeResolution::Missing) {
12714        return resolution;
12715    }
12716
12717    // A foreign header can contribute an exact using binding from a build
12718    // configuration that is compatible with, but not implied by, the current
12719    // reference. Forward navigation has no "unproven" result channel, so it
12720    // may still navigate through one unique structured import after ordinary
12721    // lookup misses. Inverse attribution keeps using its target-guided path
12722    // and records the same evidence as unproven (#940).
12723    match compatible_foreign_type_import_resolution(
12724        node,
12725        components,
12726        global,
12727        analyzer,
12728        visibility,
12729        ordinary_type_imports,
12730        file,
12731        source,
12732        &lexical_scope,
12733        None,
12734    ) {
12735        OrdinaryTypeImportResolution::Missing => resolution,
12736        OrdinaryTypeImportResolution::Resolved {
12737            target,
12738            target_components,
12739            ..
12740        } => visibility.resolve_imported_type_candidate(
12741            analyzer,
12742            file,
12743            &target,
12744            &target_components,
12745            None,
12746            true,
12747        ),
12748        OrdinaryTypeImportResolution::Ambiguous { .. } => LexicalTypeResolution::Ambiguous,
12749    }
12750}
12751
12752fn recovered_same_file_type_alias_resolution(
12753    node: Node<'_>,
12754    components: &[String],
12755    analyzer: &CppGraphSource<'_>,
12756    visibility: &VisibilityIndex<'_>,
12757    file: &ProjectFile,
12758    direct_target: Option<&CodeUnit>,
12759    lexical_scope: &[String],
12760) -> Option<LexicalTypeResolution> {
12761    debug_assert_eq!(components.len(), 1);
12762    debug_assert!(recovered_macro_decorated_type_node(node).is_some());
12763    let alias_provider = analyzer.type_alias_provider()?;
12764    for qualified in lexical_component_tiers(components, false, lexical_scope) {
12765        let candidates = visibility
12766            .visible_identifier_candidates(file, &components[0])
12767            .filter(|candidate| {
12768                candidate.source() == file
12769                    && canonical_cpp_scope_components(candidate) == qualified
12770                    && visibility
12771                        .external_type_candidate_visible_in_context(analyzer, file, candidate, node)
12772            })
12773            .collect::<Vec<_>>();
12774        if candidates.is_empty() {
12775            continue;
12776        }
12777        if candidates
12778            .iter()
12779            .any(|candidate| !alias_provider.is_type_alias(candidate))
12780        {
12781            return None;
12782        }
12783        let unit = if let Some(target) = direct_target {
12784            visibility.unique_type_candidate_preserving_target(
12785                analyzer,
12786                file,
12787                &candidates,
12788                target,
12789            )?
12790        } else {
12791            let first = candidates[0];
12792            if candidates
12793                .iter()
12794                .any(|candidate| !same_visible_symbol(candidate, first))
12795            {
12796                return None;
12797            }
12798            first.clone()
12799        };
12800        return Some(LexicalTypeResolution::Resolved {
12801            unit,
12802            components: qualified,
12803            candidates: candidates.into_iter().cloned().collect(),
12804        });
12805    }
12806    None
12807}
12808
12809fn same_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12810    matches!(
12811        structured_owner_context_resolution(node, ctx),
12812        StructuredOwnerContextResolution::SelfTarget
12813            | StructuredOwnerContextResolution::InheritedTarget
12814    )
12815}
12816
12817/// A bare/`this->` member call whose name resolves, through the enclosing class's base
12818/// hierarchy or through a lexically enclosing class, to the target member declared on
12819/// another owner. This is a genuine external usage of that owner's member rather than a
12820/// same-type self call.
12821fn inherited_target_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12822    let Some(call) = ctx.ancestry.parent(node).filter(|parent| {
12823        parent.kind() == "call_expression" && parent.child_by_field_name("function") == Some(node)
12824    }) else {
12825        return matches!(
12826            structured_owner_context_resolution(node, ctx),
12827            StructuredOwnerContextResolution::InheritedTarget
12828        );
12829    };
12830    let Some(target_owner) = ctx.spec.owner.as_ref() else {
12831        return false;
12832    };
12833    let chain = structured_enclosing_owner_chain(node, ctx);
12834    let Some(innermost) = chain.first() else {
12835        return false;
12836    };
12837    if receiver_owner_matches_target(innermost, target_owner, node.start_byte(), ctx) {
12838        return false;
12839    }
12840    let Some(arity) = ctx
12841        .visibility
12842        .call_arity_evidence(ctx.file, call, ctx.source)
12843        .exact()
12844    else {
12845        return false;
12846    };
12847    for enclosing_owner in &chain {
12848        if receiver_owner_matches_target(enclosing_owner, target_owner, node.start_byte(), ctx) {
12849            return true;
12850        }
12851        match resolve_declaring_callable_owner(
12852            &ctx.analyzer,
12853            ctx.visibility,
12854            ctx.file,
12855            cached_declaring_member_owner(enclosing_owner, ctx),
12856            &ctx.spec.member_name,
12857            arity,
12858        ) {
12859            EnclosingMemberOwnerResolution::Owner(owner) => {
12860                return receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx);
12861            }
12862            EnclosingMemberOwnerResolution::Ambiguous => return false,
12863            // The name is not declared in this class or its bases, so C++
12864            // unqualified lookup continues in the next enclosing class (#3095).
12865            EnclosingMemberOwnerResolution::Missing => {}
12866        }
12867    }
12868    false
12869}
12870
12871fn known_non_target_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12872    matches!(
12873        structured_owner_context_resolution(node, ctx),
12874        StructuredOwnerContextResolution::NonTarget
12875    )
12876}
12877
12878fn out_of_line_target_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12879    let Some(target_owner) = ctx.spec.owner.as_ref() else {
12880        return false;
12881    };
12882    let mut current = ctx.ancestry.parent(node);
12883    while let Some(parent) = current {
12884        if parent.kind() == "function_definition" {
12885            let Some(owner_lookup) = function_definition_owner_lookup_node(parent) else {
12886                return false;
12887            };
12888            if let Some(owners) = out_of_line_member_definition_owner(
12889                &ctx.analyzer,
12890                ctx.visibility,
12891                ctx.file,
12892                ctx.source,
12893                owner_lookup,
12894            ) && let Some((_, owner)) = owners.innermost()
12895            {
12896                return receiver_owner_matches_target(owner, target_owner, node.start_byte(), ctx);
12897            }
12898            if let Some(owner) = target_guided_out_of_line_owner(owner_lookup, ctx) {
12899                return receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx);
12900            }
12901            return false;
12902        }
12903        current = ctx.ancestry.parent(parent);
12904    }
12905    false
12906}
12907
12908#[derive(Clone, Copy)]
12909enum StructuredOwnerContextResolution {
12910    /// The enclosing class is itself the target owner: a bare/`this->` call here is a
12911    /// genuine same-type self call (the SelfReceiver policy from #1014-B applies).
12912    SelfTarget,
12913    /// The enclosing class does not declare the member; lookup reaches the target owner
12914    /// through a base of that class, or through a lexically enclosing class (a nested
12915    /// class calling the outer class's member). Either way the reference is a genuine
12916    /// external usage OF that owner's member (e.g. `Derived` calling inherited
12917    /// `Base::value`), not a self call, so it is attributed as an ordinary Reference.
12918    InheritedTarget,
12919    NonTarget,
12920    Ambiguous,
12921    Missing,
12922}
12923
12924fn structured_owner_context_resolution(
12925    node: Node<'_>,
12926    ctx: &ScanCtx<'_>,
12927) -> StructuredOwnerContextResolution {
12928    let Some(target_owner) = ctx.spec.owner.as_ref() else {
12929        return StructuredOwnerContextResolution::Missing;
12930    };
12931    let chain = structured_enclosing_owner_chain(node, ctx);
12932    let Some(innermost) = chain.first() else {
12933        return StructuredOwnerContextResolution::Missing;
12934    };
12935    if receiver_owner_matches_target(innermost, target_owner, node.start_byte(), ctx) {
12936        return StructuredOwnerContextResolution::SelfTarget;
12937    }
12938    // Unqualified lookup searches the enclosing class and its bases, then each lexically
12939    // enclosing class outward, and stops at the first scope that declares the name (#3095).
12940    // Only the immediately enclosing class makes a reference a same-type self call; any
12941    // other owner it reaches is a genuine usage of that owner's member.
12942    for enclosing_owner in &chain {
12943        if receiver_owner_matches_target(enclosing_owner, target_owner, node.start_byte(), ctx) {
12944            return StructuredOwnerContextResolution::InheritedTarget;
12945        }
12946        match cached_declaring_member_owner(enclosing_owner, ctx) {
12947            EnclosingMemberOwnerResolution::Owner(owner)
12948                if receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx) =>
12949            {
12950                return StructuredOwnerContextResolution::InheritedTarget;
12951            }
12952            EnclosingMemberOwnerResolution::Owner(_) => {
12953                return StructuredOwnerContextResolution::NonTarget;
12954            }
12955            EnclosingMemberOwnerResolution::Ambiguous => {
12956                return StructuredOwnerContextResolution::Ambiguous;
12957            }
12958            EnclosingMemberOwnerResolution::Missing => {}
12959        }
12960    }
12961    StructuredOwnerContextResolution::Missing
12962}
12963
12964fn cached_declaring_member_owner(
12965    receiver_owner: &CodeUnit,
12966    ctx: &ScanCtx<'_>,
12967) -> EnclosingMemberOwnerResolution {
12968    if let Some(cached) = ctx.member_owner_cache.borrow().get(receiver_owner).cloned() {
12969        return cached;
12970    }
12971    let resolved = resolve_declaring_member_owner(
12972        &ctx.analyzer,
12973        ctx.visibility,
12974        ctx.file,
12975        receiver_owner,
12976        &ctx.spec.member_name,
12977    );
12978    let resolved = if matches!(resolved, EnclosingMemberOwnerResolution::Missing) {
12979        indexed_declaring_owner_for_recovered_member(receiver_owner, ctx)
12980    } else {
12981        resolved
12982    };
12983    ctx.member_owner_cache
12984        .borrow_mut()
12985        .insert(receiver_owner.clone(), resolved.clone());
12986    resolved
12987}
12988
12989/// Recover a member's declaring owner when parser recovery omitted its
12990/// in-class declaration but retained an out-of-line definition. Ordinary
12991/// visible-member lookup runs first. The structured definition index then
12992/// supplies the missing member fact at each hierarchy level, so an indexed
12993/// derived override still hides the queried base member and distinct base
12994/// paths still fail closed.
12995fn indexed_declaring_owner_for_recovered_member(
12996    receiver_owner: &CodeUnit,
12997    ctx: &ScanCtx<'_>,
12998) -> EnclosingMemberOwnerResolution {
12999    let Some(spec_owner) = ctx.spec.owner.as_ref() else {
13000        return EnclosingMemberOwnerResolution::Missing;
13001    };
13002    if ctx.spec.kind != TargetKind::Method || ctx.spec.target.source() == spec_owner.source() {
13003        return EnclosingMemberOwnerResolution::Missing;
13004    }
13005    let Some(hierarchy) = ctx.analyzer.type_hierarchy_provider() else {
13006        return EnclosingMemberOwnerResolution::Missing;
13007    };
13008    let Some(receiver_owner) =
13009        ctx.visibility
13010            .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, receiver_owner)
13011    else {
13012        return EnclosingMemberOwnerResolution::Ambiguous;
13013    };
13014    let Some(target_owner) = ctx.spec.owner.as_ref().and_then(|owner| {
13015        ctx.visibility
13016            .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, owner)
13017    }) else {
13018        return EnclosingMemberOwnerResolution::Missing;
13019    };
13020
13021    let owner_declares_member = |owner: &CodeUnit| {
13022        if same_visible_symbol(owner, &target_owner) {
13023            return true;
13024        }
13025        let mut member_fq = owner.fq().clone();
13026        member_fq.push(
13027            ctx.spec
13028                .target
13029                .fq()
13030                .last()
13031                .expect("a method target has a terminal member segment"),
13032        );
13033        ctx.analyzer
13034            .definitions(&member_fq.display(segment_interner()))
13035            .any(|child| child.is_function())
13036    };
13037    if owner_declares_member(&receiver_owner) {
13038        return EnclosingMemberOwnerResolution::Owner(receiver_owner);
13039    }
13040
13041    let mut stack = hierarchy.get_direct_ancestors(&receiver_owner);
13042    let mut propagated_counts: HashMap<CodeUnit, u8> = HashMap::default();
13043    let mut declaring_owner = None;
13044    while let Some(raw_owner) = stack.pop() {
13045        let Some(owner) =
13046            ctx.visibility
13047                .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, &raw_owner)
13048        else {
13049            return EnclosingMemberOwnerResolution::Ambiguous;
13050        };
13051        let propagated = propagated_counts.entry(owner.clone()).or_default();
13052        if *propagated == 2 {
13053            continue;
13054        }
13055        *propagated += 1;
13056        if owner_declares_member(&owner) {
13057            if declaring_owner.is_some() {
13058                return EnclosingMemberOwnerResolution::Ambiguous;
13059            }
13060            declaring_owner = Some(owner);
13061            continue;
13062        }
13063        stack.extend(hierarchy.get_direct_ancestors(&owner));
13064    }
13065    declaring_owner
13066        .map(EnclosingMemberOwnerResolution::Owner)
13067        .unwrap_or(EnclosingMemberOwnerResolution::Missing)
13068}
13069
13070/// The lexically enclosing classes at a reference, innermost first: C++ unqualified
13071/// lookup searches each in turn before it reaches the enclosing namespaces.
13072fn structured_enclosing_owner_chain(node: Node<'_>, ctx: &ScanCtx<'_>) -> Vec<CodeUnit> {
13073    let Some(innermost) = structured_enclosing_owner(node, ctx) else {
13074        return Vec::new();
13075    };
13076    // The innermost owner is whatever enclosing-owner resolution produced, so
13077    // it is kept as given; only the walk outward is filtered to classes.
13078    brokk_bifrost_core::analyzer::usages::common::enclosing_class_chain(innermost, |unit| {
13079        ctx.analyzer.parent_of(unit)
13080    })
13081    .collect()
13082}
13083
13084fn structured_enclosing_owner(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
13085    // Declaration recovery can index the true class/member ranges even when
13086    // the original error tree wraps that region in a bogus function. Prefer
13087    // the analyzer's exact enclosing-owner graph at the reference byte before
13088    // interpreting such a wrapper as a real callable owner.
13089    if (has_recovered_class_shape_ancestor(node)
13090        || has_malformed_wrapper_function_definition_ancestor(node))
13091        && let Some(owner) = cached_indexed_enclosing_class_owner(node, ctx)
13092    {
13093        return Some(owner);
13094    }
13095    let mut current = ctx.ancestry.parent(node);
13096    while let Some(parent) = current {
13097        if parent.kind() == "function_definition" {
13098            let owner_lookup = function_definition_owner_lookup_node(parent);
13099            if let Some(owner_lookup) = owner_lookup
13100                && let Some(owners) = out_of_line_member_definition_owner(
13101                    &ctx.analyzer,
13102                    ctx.visibility,
13103                    ctx.file,
13104                    ctx.source,
13105                    owner_lookup,
13106                )
13107                && let Some((_, owner)) = owners.innermost()
13108            {
13109                return Some(owner.clone());
13110            }
13111            if let Some(owner) = cached_indexed_enclosing_class_owner(parent, ctx) {
13112                return Some(owner);
13113            }
13114            if let Some(owner) = enclosing_context(parent, ctx)
13115                .owner
13116                .filter(|owner| owner.is_class())
13117            {
13118                return Some(owner);
13119            }
13120            if let Some(owner_lookup) = owner_lookup
13121                && let Some(owner) = target_guided_out_of_line_owner(owner_lookup, ctx)
13122            {
13123                return Some(owner);
13124            }
13125            break;
13126        }
13127        current = ctx.ancestry.parent(parent);
13128    }
13129    enclosing_context(node, ctx)
13130        .owner
13131        .filter(|owner| owner.is_class())
13132}
13133
13134fn target_guided_out_of_line_owner(function: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
13135    let target_owner = ctx.spec.owner.as_ref()?;
13136    let (owner_components, _) = qualified_callable_owner_components(function, ctx.source)?;
13137    let owner_name = owner_components.last()?;
13138    let mut candidates = Vec::new();
13139    for candidate in ctx
13140        .visibility
13141        .visible_identifier_candidates(ctx.file, owner_name)
13142        .filter(|candidate| candidate.is_class())
13143    {
13144        let components = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
13145            brokk_bifrost_core::analyzer::Language::Cpp,
13146            &cpp_name_for(candidate),
13147        );
13148        if !components.ends_with(&owner_components)
13149            || candidates
13150                .iter()
13151                .any(|existing| same_logical_symbol(existing, candidate))
13152        {
13153            continue;
13154        }
13155        candidates.push(candidate.clone());
13156    }
13157    let [candidate] = candidates.as_slice() else {
13158        return None;
13159    };
13160    (same_logical_symbol(candidate, target_owner)
13161        && target_group_contains_owner_peer(candidate, ctx))
13162    .then(|| candidate.clone())
13163}