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 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, ¯o_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
288fn 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
485pub 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 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 if parent.kind() == "namespace_definition" {
745 return false;
746 }
747 if parent.kind() == "function_definition" {
748 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 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
865fn scan_owner_type<'a>(ctx: &'a ScanCtx<'_>) -> Option<&'a CodeUnit> {
878 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
937pub 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 WalkControl::SkipChildren
988 }
989 }
990 _ => WalkControl::Continue,
991 });
992 spelled
993}
994
995pub 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 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 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 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 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 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 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 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
1958fn target_guided_nested_type_terminal_hit<'tree>(
1965 node: Node<'tree>,
1966 ctx: &ScanCtx<'_>,
1967) -> Option<Node<'tree>> {
1968 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 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
2208fn 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
2279fn 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
2347fn 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
2416fn 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
2467fn 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 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
2591fn 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
2728fn 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
2820fn 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 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 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
2909fn 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 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 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
3297fn 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 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#[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 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 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 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 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 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 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 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
3975enum 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 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
4063fn 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
4141fn 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
4244fn 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
4273fn 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
4582fn 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
4649fn 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
4710fn 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 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 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 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
4882fn 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
4981fn 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
5015fn 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
5045fn 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
5127fn 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 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
5187fn 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 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 ctx.visibility
5247 .external_type_candidate_visible_in_context(&ctx.analyzer, ctx.file, target, node)
5248 .then_some(node)
5249}
5250
5251fn 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 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
5314fn 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
5449pub 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
5500fn 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
5524fn 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
5894fn 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 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
6188enum ConstructorOverloadSelection {
6191 Target,
6195 Ambiguous,
6198 OtherOverload,
6200}
6201
6202fn 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 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 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 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 } 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
6474fn 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
6551fn 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
6636fn 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 "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 "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 "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
6709fn 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
6730fn 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
6762fn 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 } else {
6804 push_unproven_hit(node, ctx);
6805 }
6806}
6807
6808#[derive(Clone, Copy)]
6809enum RecoveredCallableDeclarationKind {
6810 Declaration,
6811 Definition,
6812}
6813
6814fn 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 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 }
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 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 }
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
7123fn 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 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 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 Parameter,
7246 Units(Vec<CodeUnit>),
7248 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 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
7308fn 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
7371fn 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 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 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 }
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
7744pub 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 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
7904fn 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
7954fn 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 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 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 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 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
8389fn 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
8432pub enum QualifiedReceiverBase {
8439 Variable(Vec<CodeUnit>),
8441 Type(Option<CodeUnit>),
8443 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 "identifier" | "field_identifier" => {
8512 let name = node_text(current, source);
8513 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 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 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 "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 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
8761fn 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 {
8819 let alias_provider = ctx.analyzer.type_alias_provider()?;
8820 let concrete = ctx
8821 .visibility
8822 .visible_identifier_candidates(ctx.file, &components[1])
8823 .filter(|candidate| {
8824 alias_provider.is_type_alias(candidate)
8825 && !same_visible_symbol(candidate, alias)
8826 && type_owner_of(&ctx.analyzer, candidate).is_some_and(|owner| owner.is_class())
8827 && ctx.visibility.is_physically_visible(ctx.file, candidate)
8828 && ctx
8829 .visibility
8830 .external_type_candidate_guard_compatible_in_context(
8831 &ctx.analyzer,
8832 ctx.file,
8833 candidate,
8834 type_node,
8835 )
8836 })
8837 .filter_map(|candidate| {
8838 let canonical = ctx.visibility.canonical_visible_full_type_unit(
8839 &ctx.analyzer,
8840 ctx.file,
8841 candidate,
8842 )?;
8843 (!same_visible_symbol(&canonical, candidate)).then_some(canonical)
8848 })
8849 .collect::<Vec<_>>();
8850 if let [unit] = unanimous_receiver_units(concrete).as_slice()
8851 && same_visible_symbol(unit, &target)
8852 {
8853 return Some(target);
8854 }
8855 }
8856 let scope = ctx
8857 .recovered_sentinel_scope(type_node)
8858 .or_else(|| indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, type_node))?;
8859 let path_matches = indexed_scope_matches_target_name(&scope, &components, global, &target);
8860 let visible = ctx.visibility.external_type_candidate_visible_in_context(
8861 &ctx.analyzer,
8862 ctx.file,
8863 &target,
8864 type_node,
8865 );
8866 (path_matches && visible).then_some(target)
8867}
8868
8869fn receiver_type_name_unit(node: Node<'_>, type_name: &str, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
8870 let normalized = normalize_cpp_type_name(type_name);
8871 if normalized.is_empty() {
8872 return None;
8873 }
8874
8875 if let Some(alias_type) = local_receiver_alias_type_node(node, &normalized, ctx) {
8880 match resolve_receiver_type_node(alias_type, ctx) {
8881 Ok(Some(unit)) => return Some(unit),
8882 Err(_) => return None,
8883 Ok(None) => {}
8884 }
8885 }
8886
8887 match resolve_receiver_type_name_lexically(node, &normalized, ctx) {
8888 LexicalTypeResolution::Resolved { unit, .. } => return Some(unit),
8889 LexicalTypeResolution::Ambiguous => return None,
8890 LexicalTypeResolution::Missing => {}
8891 }
8892 let candidates = ctx
8893 .visibility
8894 .type_name_candidates(ctx.file, &normalized)
8895 .into_iter()
8896 .filter_map(|candidate| canonical_receiver_unit(candidate, ctx))
8897 .collect();
8898 unanimous_receiver_units(candidates).into_iter().next()
8899}
8900
8901fn resolve_receiver_type_node(
8909 type_node: Node<'_>,
8910 ctx: &ScanCtx<'_>,
8911) -> std::result::Result<Option<CodeUnit>, CppTemplateResolutionError> {
8912 let type_node = receiver_type_node_base(type_node);
8913 if let Some(unit) = ctx
8914 .visibility
8915 .resolve_type_node_result(ctx.file, type_node, ctx.source)?
8916 {
8917 return Ok(Some(unit));
8918 }
8919 Ok(resolve_receiver_type_node_lexically(type_node, ctx))
8920}
8921
8922fn resolve_receiver_type_node_lexically(
8923 type_node: Node<'_>,
8924 ctx: &ScanCtx<'_>,
8925) -> Option<CodeUnit> {
8926 let type_node = receiver_type_node_base(type_node);
8927 let components = cpp_type_name_components(type_node, ctx.source)?;
8928 let lexical_scope = match enclosing_lexical_scope_components(
8929 type_node,
8930 &ctx.analyzer,
8931 ctx.visibility,
8932 ctx.file,
8933 ctx.source,
8934 ) {
8935 LexicalScopeResolution::Resolved(scope) => scope,
8936 LexicalScopeResolution::Ambiguous | LexicalScopeResolution::Missing => return None,
8937 };
8938 match ctx.visibility.resolve_type_components_lexically(
8939 &ctx.analyzer,
8940 ctx.file,
8941 &components,
8942 is_globally_qualified_cpp_name(type_node),
8943 &lexical_scope,
8944 ) {
8945 LexicalTypeResolution::Resolved { unit, .. } => Some(unit),
8946 LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
8947 }
8948}
8949
8950fn receiver_type_node_base(mut node: Node<'_>) -> Node<'_> {
8951 while matches!(node.kind(), "type_descriptor" | "dependent_type") {
8952 let Some(inner) = node.child_by_field_name("type").or_else(|| {
8953 if node.kind() == "dependent_type" {
8954 node.named_child(0)
8955 } else {
8956 None
8957 }
8958 }) else {
8959 break;
8960 };
8961 node = inner;
8962 }
8963 node
8964}
8965
8966fn resolve_receiver_type_name_lexically(
8967 node: Node<'_>,
8968 normalized: &str,
8969 ctx: &ScanCtx<'_>,
8970) -> LexicalTypeResolution {
8971 let components = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
8972 brokk_bifrost_core::analyzer::Language::Cpp,
8973 normalized,
8974 );
8975 if components.is_empty() {
8976 return LexicalTypeResolution::Missing;
8977 }
8978 let lexical_scope = match enclosing_lexical_scope_components(
8979 node,
8980 &ctx.analyzer,
8981 ctx.visibility,
8982 ctx.file,
8983 ctx.source,
8984 ) {
8985 LexicalScopeResolution::Resolved(scope) => scope,
8986 LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
8987 LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
8988 };
8989 ctx.visibility.resolve_type_components_lexically(
8990 &ctx.analyzer,
8991 ctx.file,
8992 &components,
8993 normalized.starts_with("::"),
8994 &lexical_scope,
8995 )
8996}
8997
8998fn local_receiver_alias_type_node<'tree>(
8999 node: Node<'tree>,
9000 name: &str,
9001 ctx: &ScanCtx<'_>,
9002) -> Option<Node<'tree>> {
9003 let callable = nearest_callable_scope(node)?;
9004 let mut root_callable = callable;
9005 let mut ancestor = callable.parent();
9008 while let Some(current) = ancestor {
9009 if matches!(current.kind(), "function_definition" | "lambda_expression") {
9010 root_callable = current;
9011 }
9012 ancestor = current.parent();
9013 }
9014
9015 let mut stack = vec![root_callable];
9016 let mut best = None;
9017 while let Some(current) = stack.pop() {
9018 if current.start_byte() >= node.start_byte() {
9019 continue;
9020 }
9021 if local_type_alias_name_node(current)
9022 .is_some_and(|alias_name| node_text(alias_name, ctx.source) == name)
9023 && local_alias_scope_contains_node(current, node)
9024 {
9025 let replace = best
9026 .is_none_or(|existing: Node<'tree>| existing.start_byte() < current.start_byte());
9027 if replace {
9028 best = current.child_by_field_name("type");
9029 }
9030 }
9031 let mut cursor = current.walk();
9032 stack.extend(current.named_children(&mut cursor));
9033 }
9034 best
9035}
9036
9037fn canonical_receiver_units(units: Vec<CodeUnit>, ctx: &ScanCtx<'_>) -> Vec<CodeUnit> {
9038 let mut canonical = Vec::with_capacity(units.len());
9039 for unit in units {
9040 let Some(unit) = canonical_receiver_unit(&unit, ctx) else {
9041 return Vec::new();
9042 };
9043 canonical.push(unit);
9044 }
9045 unanimous_receiver_units(canonical)
9046}
9047
9048fn canonical_receiver_unit(unit: &CodeUnit, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
9049 if let Some(cached) = ctx.receiver_canonical_type_cache.borrow().get(unit) {
9050 return cached.clone();
9051 }
9052 let canonical = ctx
9053 .visibility
9054 .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, unit);
9055 ctx.receiver_canonical_type_cache
9056 .borrow_mut()
9057 .insert(unit.clone(), canonical.clone());
9058 canonical
9059}
9060
9061fn receiver_units_from_declared_fields(
9062 fields: Vec<&CodeUnit>,
9063 reference: Node<'_>,
9064 ctx: &ScanCtx<'_>,
9065) -> Vec<CodeUnit> {
9066 let Some(first) = fields.first() else {
9067 return Vec::new();
9068 };
9069 if fields
9070 .iter()
9071 .skip(1)
9072 .any(|field| !same_visible_symbol(first, field))
9073 {
9074 return Vec::new();
9075 }
9076 unanimous_receiver_units(
9077 fields
9078 .into_iter()
9079 .filter_map(|field| {
9080 field_declared_binding(&ctx.analyzer, ctx.visibility, ctx.file, field)
9081 .and_then(|binding| binding.unit)
9082 .or_else(|| recovered_receiver_field_type(reference, field, ctx))
9083 })
9084 .collect(),
9085 )
9086}
9087
9088fn recovered_receiver_field_type(
9093 reference: Node<'_>,
9094 field: &CodeUnit,
9095 ctx: &ScanCtx<'_>,
9096) -> Option<CodeUnit> {
9097 let target = ctx.spec.owner.as_ref()?.clone();
9098 if !target.is_class() || field.source() != ctx.file {
9099 return None;
9100 }
9101 let range = ctx
9102 .analyzer
9103 .ranges(field)
9104 .into_iter()
9105 .find(|range| range.start_byte < range.end_byte)?;
9106 let mut declaration =
9107 root_node(reference).descendant_for_byte_range(range.start_byte, range.end_byte)?;
9108 while !matches!(declaration.kind(), "declaration" | "field_declaration") {
9109 declaration = ctx.ancestry.parent(declaration)?;
9110 }
9111 let type_node = first_type_child(declaration)?;
9112 let resolution = resolve_type_node_lexically_for_target(
9113 type_node,
9114 &ctx.analyzer,
9115 ctx.visibility,
9116 &ctx.ordinary_type_imports,
9117 ctx.file,
9118 ctx.source,
9119 &target,
9120 Some(&ctx.lexical_scope_cache),
9121 ctx.recovered_sentinel_scope(type_node).as_deref(),
9122 );
9123 if let LexicalTypeResolution::Resolved {
9124 unit, candidates, ..
9125 } = resolution
9126 && (same_visible_symbol(&unit, &target)
9127 || candidates
9128 .iter()
9129 .any(|candidate| same_visible_symbol(candidate, &target)))
9130 {
9131 return Some(target);
9132 }
9133 let type_node = receiver_type_node_base(type_node);
9134 let (components, global) = type_reference_components(type_node, ctx.source)?;
9135 let scope = ctx
9136 .recovered_sentinel_scope(type_node)
9137 .or_else(|| indexed_enclosing_lexical_scope(&ctx.analyzer, ctx.file, type_node))?;
9138 (indexed_scope_matches_target_name(&scope, &components, global, &target)
9139 && ctx.visibility.external_type_candidate_visible_in_context(
9140 &ctx.analyzer,
9141 ctx.file,
9142 &target,
9143 type_node,
9144 ))
9145 .then_some(target)
9146}
9147
9148fn unanimous_receiver_units(units: Vec<CodeUnit>) -> Vec<CodeUnit> {
9149 let mut unique = Vec::new();
9150 for unit in units {
9151 if !unique
9152 .iter()
9153 .any(|existing| same_visible_symbol(existing, &unit))
9154 {
9155 unique.push(unit);
9156 if unique.len() > 1 {
9157 return Vec::new();
9158 }
9159 }
9160 }
9161 unique
9162}
9163
9164fn receiver_matches_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9165 let Some(owner) = ctx.spec.owner.as_ref() else {
9166 return false;
9167 };
9168 match node.kind() {
9169 "field_expression" => false,
9176 "call_expression" => node
9177 .child_by_field_name("function")
9178 .is_some_and(|function| receiver_matches_target(function, ctx)),
9179 "pointer_expression" | "parenthesized_expression" | "subscript_expression" => node
9180 .child_by_field_name("argument")
9181 .or_else(|| node.named_child(0))
9182 .is_some_and(|child| receiver_matches_target(child, ctx)),
9183 "identifier" | "this" if ctx.analyzer.reference_uses_c_semantics(ctx.file) => ctx
9184 .bindings
9185 .resolve_symbol(node_text(node, ctx.source))
9186 .as_precise()
9187 .is_some_and(|targets| {
9188 targets
9189 .iter()
9190 .filter_map(|target| target.unit.as_ref())
9191 .any(|target| {
9192 receiver_owner_matches_target(target, owner, node.start_byte(), ctx)
9193 })
9194 }),
9195 "this" => same_owner_context(node, ctx),
9196 _ => qualified_owner_matches(node, ctx),
9197 }
9198}
9199
9200fn declaring_owner_for_explicit_receiver(
9201 receiver: Node<'_>,
9202 call_arity: Option<usize>,
9203 ctx: &ScanCtx<'_>,
9204) -> EnclosingMemberOwnerResolution {
9205 if receiver_is_self_like(receiver, ctx.analyzer.reference_uses_c_semantics(ctx.file)) {
9206 return EnclosingMemberOwnerResolution::Missing;
9207 }
9208 declaring_owner_from_receiver_units(
9209 receiver_type_units(receiver, ctx.source, ctx),
9210 receiver.start_byte(),
9211 call_arity,
9212 ctx,
9213 )
9214}
9215
9216fn declaring_owner_from_receiver_units(
9223 receiver_units: Vec<CodeUnit>,
9224 reference_byte: usize,
9225 call_arity: Option<usize>,
9226 ctx: &ScanCtx<'_>,
9227) -> EnclosingMemberOwnerResolution {
9228 let mut declaring_owner = None;
9229 for receiver_owner in receiver_units {
9230 if ctx.spec.owner.as_ref().is_some_and(|target_owner| {
9231 receiver_owner_matches_target(&receiver_owner, target_owner, reference_byte, ctx)
9232 }) {
9233 if declaring_owner
9234 .as_ref()
9235 .is_some_and(|existing| !same_visible_symbol(existing, &receiver_owner))
9236 {
9237 return EnclosingMemberOwnerResolution::Ambiguous;
9238 }
9239 declaring_owner = Some(receiver_owner);
9240 continue;
9241 }
9242 let ordinary = cached_declaring_member_owner(&receiver_owner, ctx);
9243 let owner_resolution = match call_arity {
9244 Some(arity) => resolve_declaring_callable_owner(
9245 &ctx.analyzer,
9246 ctx.visibility,
9247 ctx.file,
9248 ordinary,
9249 &ctx.spec.member_name,
9250 arity,
9251 ),
9252 None => ordinary,
9253 };
9254 match owner_resolution {
9255 EnclosingMemberOwnerResolution::Owner(owner) => {
9256 if declaring_owner
9257 .as_ref()
9258 .is_some_and(|existing| !same_visible_symbol(existing, &owner))
9259 {
9260 return EnclosingMemberOwnerResolution::Ambiguous;
9261 }
9262 declaring_owner = Some(owner);
9263 }
9264 EnclosingMemberOwnerResolution::Ambiguous => {
9265 return EnclosingMemberOwnerResolution::Ambiguous;
9266 }
9267 EnclosingMemberOwnerResolution::Missing => {}
9268 }
9269 }
9270 declaring_owner
9271 .map(EnclosingMemberOwnerResolution::Owner)
9272 .unwrap_or(EnclosingMemberOwnerResolution::Missing)
9273}
9274
9275fn declaring_owner_from_call_function(
9276 function: Node<'_>,
9277 call_arity: Option<usize>,
9278 ctx: &ScanCtx<'_>,
9279) -> Option<EnclosingMemberOwnerResolution> {
9280 match function.kind() {
9281 "field_expression" => function
9282 .child_by_field_name("argument")
9283 .or_else(|| function.child_by_field_name("object"))
9284 .map(|receiver| declaring_owner_for_explicit_receiver(receiver, call_arity, ctx))
9285 .or(Some(EnclosingMemberOwnerResolution::Missing)),
9286 "call_expression" => function
9287 .child_by_field_name("function")
9288 .and_then(|inner| declaring_owner_from_call_function(inner, call_arity, ctx)),
9289 _ => None,
9290 }
9291}
9292
9293enum MethodReceiverTargetResolution {
9294 Target,
9295 NonTarget,
9296 Ambiguous,
9297 Missing,
9298}
9299
9300fn method_receiver_target_resolution(
9301 node: Node<'_>,
9302 declaring_owner: EnclosingMemberOwnerResolution,
9303 ctx: &ScanCtx<'_>,
9304) -> MethodReceiverTargetResolution {
9305 match declaring_owner {
9306 EnclosingMemberOwnerResolution::Owner(_) | EnclosingMemberOwnerResolution::Ambiguous => {
9307 declaring_owner_target_resolution(declaring_owner, node.start_byte(), ctx)
9308 }
9309 EnclosingMemberOwnerResolution::Missing if ctx.spec.owner.is_none() => {
9310 MethodReceiverTargetResolution::Missing
9311 }
9312 EnclosingMemberOwnerResolution::Missing if receiver_matches_target(node, ctx) => {
9313 MethodReceiverTargetResolution::Target
9314 }
9315 EnclosingMemberOwnerResolution::Missing if receiver_has_known_non_target(node, ctx) => {
9316 MethodReceiverTargetResolution::NonTarget
9317 }
9318 EnclosingMemberOwnerResolution::Missing => MethodReceiverTargetResolution::Missing,
9319 }
9320}
9321
9322fn declaring_owner_target_resolution(
9329 declaring_owner: EnclosingMemberOwnerResolution,
9330 reference_byte: usize,
9331 ctx: &ScanCtx<'_>,
9332) -> MethodReceiverTargetResolution {
9333 let Some(target_owner) = ctx.spec.owner.as_ref() else {
9334 return MethodReceiverTargetResolution::Missing;
9335 };
9336 match declaring_owner {
9337 EnclosingMemberOwnerResolution::Owner(owner)
9338 if receiver_owner_matches_target(&owner, target_owner, reference_byte, ctx) =>
9339 {
9340 MethodReceiverTargetResolution::Target
9341 }
9342 EnclosingMemberOwnerResolution::Owner(owner)
9343 if receiver_owner_is_known_non_target(&owner, target_owner, reference_byte, ctx) =>
9344 {
9345 MethodReceiverTargetResolution::NonTarget
9346 }
9347 EnclosingMemberOwnerResolution::Owner(_) | EnclosingMemberOwnerResolution::Missing => {
9348 MethodReceiverTargetResolution::Missing
9349 }
9350 EnclosingMemberOwnerResolution::Ambiguous => MethodReceiverTargetResolution::Ambiguous,
9351 }
9352}
9353
9354fn explicit_receiver_target_resolution(
9355 receiver: Node<'_>,
9356 call_arity: Option<usize>,
9357 ctx: &ScanCtx<'_>,
9358) -> MethodReceiverTargetResolution {
9359 method_receiver_target_resolution(
9360 receiver,
9361 declaring_owner_for_explicit_receiver(receiver, call_arity, ctx),
9362 ctx,
9363 )
9364}
9365
9366fn call_function_target_resolution(
9367 function: Node<'_>,
9368 ctx: &ScanCtx<'_>,
9369) -> MethodReceiverTargetResolution {
9370 let call_arity = ctx.ancestry.parent(function).and_then(|call| {
9371 (call.kind() == "call_expression")
9372 .then(|| {
9373 ctx.visibility
9374 .call_arity_evidence(ctx.file, call, ctx.source)
9375 .exact()
9376 })
9377 .flatten()
9378 });
9379 let Some(declaring_owner) = declaring_owner_from_call_function(function, call_arity, ctx)
9380 else {
9381 return MethodReceiverTargetResolution::Missing;
9385 };
9386 method_receiver_target_resolution(function, declaring_owner, ctx)
9387}
9388
9389fn receiver_owner_matches_target(
9390 receiver_owner: &CodeUnit,
9391 target_owner: &CodeUnit,
9392 reference_byte: usize,
9393 ctx: &ScanCtx<'_>,
9394) -> bool {
9395 same_symbol(receiver_owner, target_owner)
9396 || same_logical_symbol(receiver_owner, target_owner)
9397 && (ctx.visibility.is_physically_visible(ctx.file, target_owner)
9398 || (ctx.spec.owner_is_forward_declaration
9399 && ctx
9400 .visibility
9401 .is_physically_visible(ctx.file, receiver_owner))
9402 || visible_target_peer_matches_owner(receiver_owner, reference_byte, ctx)
9403 || target_group_contains_owner_peer(receiver_owner, ctx))
9404}
9405
9406fn receiver_owner_is_known_non_target(
9407 receiver_owner: &CodeUnit,
9408 target_owner: &CodeUnit,
9409 reference_byte: usize,
9410 ctx: &ScanCtx<'_>,
9411) -> bool {
9412 if receiver_owner_matches_target(receiver_owner, target_owner, reference_byte, ctx) {
9413 return false;
9414 }
9415 if !same_logical_symbol(receiver_owner, target_owner) {
9416 return true;
9417 }
9418 !ctx.target_group.iter().any(|target| {
9419 same_logical_symbol(target, &ctx.spec.target) && target.source() == target_owner.source()
9420 })
9421}
9422
9423fn target_group_contains_owner_peer(owner: &CodeUnit, ctx: &ScanCtx<'_>) -> bool {
9424 ctx.visibility
9425 .external_type_declaration_visible_at(ctx.file, owner, usize::MAX)
9426 && ctx.target_group.iter().any(|target| {
9427 type_owner_of(&ctx.analyzer, target)
9428 .as_ref()
9429 .is_some_and(|target_owner| owner_peer_matches(target_owner, owner))
9430 })
9431}
9432
9433fn owner_peer_matches(candidate_owner: &CodeUnit, owner: &CodeUnit) -> bool {
9434 same_symbol(candidate_owner, owner)
9435 || (same_logical_symbol(candidate_owner, owner)
9436 && candidate_owner.source() == owner.source())
9437}
9438
9439fn visible_target_peer_matches_owner(
9440 owner: &CodeUnit,
9441 reference_byte: usize,
9442 ctx: &ScanCtx<'_>,
9443) -> bool {
9444 ctx.visibility
9445 .external_type_declaration_visible_at(ctx.file, owner, reference_byte)
9446 && ctx
9447 .visibility
9448 .visible_identifier_candidates(ctx.file, &ctx.spec.member_name)
9449 .any(|candidate| {
9450 cpp_callable_definitions_share_identity_evidence(
9451 &ctx.analyzer,
9452 candidate,
9453 &ctx.spec.target,
9454 ) && ctx.visibility.declaration_visible_at(
9455 &ctx.analyzer,
9456 ctx.file,
9457 candidate,
9458 reference_byte,
9459 ) && type_owner_of(&ctx.analyzer, candidate)
9460 .as_ref()
9461 .is_some_and(|candidate_owner| owner_peer_matches(candidate_owner, owner))
9462 })
9463}
9464
9465fn call_function_has_direct_self_receiver(function: Node<'_>, reference_is_c: bool) -> bool {
9466 match function.kind() {
9467 "field_expression" => function
9468 .child_by_field_name("argument")
9469 .or_else(|| function.child_by_field_name("object"))
9470 .is_some_and(|receiver| receiver_is_self_like(receiver, reference_is_c)),
9471 _ => receiver_is_self_like(function, reference_is_c),
9472 }
9473}
9474
9475fn receiver_has_known_non_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9476 let Some(owner) = ctx.spec.owner.as_ref() else {
9477 return false;
9478 };
9479 match node.kind() {
9480 "field_expression" => node
9481 .child_by_field_name("argument")
9482 .or_else(|| node.child_by_field_name("object"))
9483 .is_some_and(|receiver| {
9484 if receiver_is_self_like(
9491 receiver,
9492 ctx.analyzer.reference_uses_c_semantics(ctx.file),
9493 ) {
9494 return false;
9495 }
9496 if receiver_is_known_function_declarator(receiver, ctx) {
9497 return true;
9498 }
9499 let units = receiver_type_units(receiver, ctx.source, ctx);
9500 !units.is_empty()
9501 && units.iter().all(|target| {
9502 receiver_owner_is_known_non_target(target, owner, node.start_byte(), ctx)
9503 })
9504 }),
9505 "call_expression" => node
9506 .child_by_field_name("function")
9507 .is_some_and(|function| receiver_has_known_non_target(function, ctx)),
9508 "pointer_expression" | "parenthesized_expression" | "subscript_expression" => node
9509 .child_by_field_name("argument")
9510 .or_else(|| node.named_child(0))
9511 .is_some_and(|child| receiver_has_known_non_target(child, ctx)),
9512 "identifier" | "this" if ctx.analyzer.reference_uses_c_semantics(ctx.file) => ctx
9513 .bindings
9514 .resolve_symbol(node_text(node, ctx.source))
9515 .as_precise()
9516 .is_some_and(|targets| {
9517 let units = targets
9518 .iter()
9519 .filter_map(|target| target.unit.as_ref())
9520 .collect::<Vec<_>>();
9521 !units.is_empty()
9522 && units.iter().all(|target| {
9523 receiver_owner_is_known_non_target(target, owner, node.start_byte(), ctx)
9524 })
9525 }),
9526 "this" => known_non_target_owner_context(node, ctx),
9527 "qualified_identifier" | "scoped_identifier" | "field_identifier" => {
9528 qualified_owner_is_known_non_target(node, ctx)
9529 }
9530 _ => false,
9531 }
9532}
9533
9534fn receiver_is_known_function_declarator(receiver: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9535 if receiver.kind() != "identifier" {
9536 return false;
9537 }
9538 let receiver_name = node_text(receiver, ctx.source);
9539 let mut current = receiver;
9540 while let Some(parent) = ctx.ancestry.parent(current) {
9541 if parent.kind() == "compound_statement" {
9542 let mut cursor = parent.walk();
9543 for statement in parent.named_children(&mut cursor) {
9544 if statement.start_byte() >= receiver.start_byte() {
9545 break;
9546 }
9547 if statement.kind() != "declaration" || statement.end_byte() > receiver.start_byte()
9548 {
9549 continue;
9550 }
9551 let type_text = statement
9552 .child_by_field_name("type")
9553 .or_else(|| first_type_child(statement))
9554 .map(|type_node| node_text(type_node, ctx.source));
9555 let mut declaration_cursor = statement.walk();
9556 for child in statement.named_children(&mut declaration_cursor) {
9557 let declarator = if child.kind() == "init_declarator" {
9558 child.child_by_field_name("declarator")
9559 } else if is_declarator_node(child) {
9560 Some(child)
9561 } else {
9562 None
9563 };
9564 let Some(declarator) = declarator else {
9565 continue;
9566 };
9567 if declarator.kind() == "function_declarator"
9568 && extract_variable_name(declarator, ctx.source)
9569 .is_some_and(|name| name == receiver_name)
9570 && function_declarator_parameters_have_known_types(declarator, ctx)
9571 && !constructor_style_local_declaration(
9572 ctx.visibility,
9573 ctx.file,
9574 ctx.source,
9575 declarator,
9576 type_text,
9577 &ctx.bindings,
9578 )
9579 {
9580 return true;
9581 }
9582 }
9583 }
9584 return false;
9585 }
9586 current = parent;
9587 }
9588 false
9589}
9590
9591fn function_declarator_parameters_have_known_types(
9592 declarator: Node<'_>,
9593 ctx: &ScanCtx<'_>,
9594) -> bool {
9595 let Some(parameters) = declarator.child_by_field_name("parameters") else {
9596 return false;
9597 };
9598 let mut cursor = parameters.walk();
9599 parameters.named_children(&mut cursor).all(|parameter| {
9600 if !matches!(
9601 parameter.kind(),
9602 "parameter_declaration" | "optional_parameter_declaration"
9603 ) {
9604 return false;
9605 }
9606 let Some(type_node) = parameter
9607 .child_by_field_name("type")
9608 .or_else(|| first_type_child(parameter))
9609 else {
9610 return false;
9611 };
9612 type_node.kind() == "primitive_type"
9613 || ctx
9614 .visibility
9615 .resolve_type_node_result(ctx.file, type_node, ctx.source)
9616 .ok()
9617 .flatten()
9618 .is_some()
9619 })
9620}
9621
9622#[derive(Clone, Copy, PartialEq, Eq)]
9623enum QualifiedOwnerResolution {
9624 Target,
9625 NonTarget,
9626 Unresolved,
9627}
9628
9629#[derive(Clone)]
9630pub enum LexicalScopeResolution {
9631 Resolved(Vec<String>),
9632 Ambiguous,
9633 Missing,
9634}
9635
9636pub struct LexicalScopeCache {
9640 resolutions: RefCell<HashMap<(usize, usize, bool, bool), LexicalScopeResolution>>,
9641 orphaned: Arc<OrphanedNamespaceScopeIndex>,
9642}
9643
9644impl LexicalScopeCache {
9645 fn new(visibility: &VisibilityIndex<'_>, file: &ProjectFile) -> Self {
9646 Self {
9647 resolutions: RefCell::new(HashMap::default()),
9648 orphaned: orphaned_namespace_scopes(visibility, file),
9649 }
9650 }
9651}
9652
9653fn orphaned_namespace_scopes(
9656 visibility: &VisibilityIndex<'_>,
9657 file: &ProjectFile,
9658) -> Arc<OrphanedNamespaceScopeIndex> {
9659 visibility
9660 .cpp()
9661 .orphaned_namespace_scopes(visibility.token(), file)
9662}
9663
9664fn qualified_owner_matches(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9665 qualified_owner_resolution(node, ctx) == QualifiedOwnerResolution::Target
9666}
9667
9668fn qualified_owner_is_known_non_target(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
9669 qualified_owner_resolution(node, ctx) == QualifiedOwnerResolution::NonTarget
9670}
9671
9672fn is_structurally_qualified(node: Node<'_>) -> bool {
9673 matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
9674 && qualified_name_has_concrete_scope_separators(node)
9675}
9676
9677fn qualified_owner_resolution(node: Node<'_>, ctx: &ScanCtx<'_>) -> QualifiedOwnerResolution {
9678 let Some(target_owner) = ctx.spec.owner.as_ref() else {
9679 return QualifiedOwnerResolution::Unresolved;
9680 };
9681 let Some((components, global)) = qualified_callable_owner_components(node, ctx.source) else {
9682 return QualifiedOwnerResolution::Unresolved;
9683 };
9684 if !global
9690 && !matches!(
9691 enclosing_lexical_scope_components(
9692 node,
9693 &ctx.analyzer,
9694 ctx.visibility,
9695 ctx.file,
9696 ctx.source,
9697 ),
9698 LexicalScopeResolution::Resolved(_)
9699 )
9700 {
9701 return QualifiedOwnerResolution::Unresolved;
9702 }
9703 match resolve_type_components_lexically_at_for_target_with_scope_cache(
9704 node,
9705 &components,
9706 global,
9707 &ctx.analyzer,
9708 ctx.visibility,
9709 &ctx.ordinary_type_imports,
9710 ctx.file,
9711 ctx.source,
9712 target_owner,
9713 false,
9714 Some(&ctx.lexical_scope_cache),
9715 ) {
9716 LexicalTypeResolution::Resolved { unit: owner, .. } => {
9717 if receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx) {
9718 return QualifiedOwnerResolution::Target;
9719 }
9720 match cached_declaring_member_owner(&owner, ctx) {
9721 EnclosingMemberOwnerResolution::Owner(declaring_owner)
9722 if receiver_owner_matches_target(
9723 &declaring_owner,
9724 target_owner,
9725 node.start_byte(),
9726 ctx,
9727 ) =>
9728 {
9729 QualifiedOwnerResolution::Target
9730 }
9731 EnclosingMemberOwnerResolution::Owner(declaring_owner)
9732 if receiver_owner_is_known_non_target(
9733 &declaring_owner,
9734 target_owner,
9735 node.start_byte(),
9736 ctx,
9737 ) =>
9738 {
9739 QualifiedOwnerResolution::NonTarget
9740 }
9741 EnclosingMemberOwnerResolution::Owner(_)
9742 | EnclosingMemberOwnerResolution::Ambiguous => QualifiedOwnerResolution::Unresolved,
9743 EnclosingMemberOwnerResolution::Missing
9744 if same_visible_symbol(&owner, target_owner) =>
9745 {
9746 QualifiedOwnerResolution::Unresolved
9747 }
9748 EnclosingMemberOwnerResolution::Missing => QualifiedOwnerResolution::NonTarget,
9749 }
9750 }
9751 LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => {
9752 QualifiedOwnerResolution::Unresolved
9753 }
9754 }
9755}
9756
9757fn qualified_callable_owner_components(
9758 node: Node<'_>,
9759 source: &str,
9760) -> Option<(Vec<String>, bool)> {
9761 if !matches!(node.kind(), "qualified_identifier" | "scoped_identifier")
9762 || !qualified_name_has_concrete_scope_separators(node)
9763 {
9764 return None;
9765 }
9766 let owner = qualified_owner_components(node, source)?;
9767 Some((owner.names, owner.global))
9768}
9769
9770fn type_reference_components(node: Node<'_>, source: &str) -> Option<(Vec<String>, bool)> {
9771 if !matches!(
9772 node.kind(),
9773 "identifier"
9774 | "type_identifier"
9775 | "namespace_identifier"
9776 | "qualified_identifier"
9777 | "scoped_identifier"
9778 | "scoped_type_identifier"
9779 | "template_type"
9780 | "template_function"
9781 ) {
9782 return None;
9783 }
9784 let components = cpp_type_name_components(node, source)?;
9785 (!components.is_empty()).then_some((components, is_globally_qualified_cpp_name(node)))
9786}
9787
9788pub fn enclosing_namespace_components(node: Node<'_>, source: &str) -> Vec<String> {
9789 let mut namespaces = Vec::new();
9790 for parent in enclosing_cpp_namespace_nodes(node) {
9791 if let Some(name) = parent.child_by_field_name("name") {
9792 let mut components = Vec::new();
9793 if append_cpp_name_components(name, source, &mut components).is_some() {
9794 namespaces.push(components);
9795 }
9796 }
9797 }
9798 namespaces.into_iter().flatten().collect()
9799}
9800
9801pub fn enclosing_lexical_scope_components(
9802 node: Node<'_>,
9803 analyzer: &CppGraphSource<'_>,
9804 visibility: &VisibilityIndex<'_>,
9805 file: &ProjectFile,
9806 source: &str,
9807) -> LexicalScopeResolution {
9808 enclosing_lexical_scope_components_with_unresolved_owner(
9809 node,
9810 analyzer,
9811 visibility,
9812 file,
9813 source,
9814 false,
9815 false,
9816 &orphaned_namespace_scopes(visibility, file),
9817 )
9818}
9819
9820#[allow(clippy::too_many_arguments)]
9821fn cached_enclosing_lexical_scope_components_with_unresolved_owner(
9822 node: Node<'_>,
9823 analyzer: &CppGraphSource<'_>,
9824 visibility: &VisibilityIndex<'_>,
9825 file: &ProjectFile,
9826 source: &str,
9827 allow_structured_unresolved_owner: bool,
9828 ignore_function_owner: bool,
9829 cache: Option<&LexicalScopeCache>,
9830) -> LexicalScopeResolution {
9831 let Some(cache) = cache else {
9832 return enclosing_lexical_scope_components_with_unresolved_owner(
9833 node,
9834 analyzer,
9835 visibility,
9836 file,
9837 source,
9838 allow_structured_unresolved_owner,
9839 ignore_function_owner,
9840 &orphaned_namespace_scopes(visibility, file),
9841 );
9842 };
9843 let orphaned = &cache.orphaned;
9844 let (anchor_start, anchor_end) = lexical_scope_cache_anchor(node);
9845 let (anchor_start, anchor_end) = match orphaned.region_at(node.start_byte()) {
9849 Some(region) => (anchor_start.max(region.start), anchor_end.min(region.end)),
9850 None => (anchor_start, anchor_end),
9851 };
9852 let key = (
9853 anchor_start,
9854 anchor_end,
9855 allow_structured_unresolved_owner,
9856 ignore_function_owner,
9857 );
9858 if let Some(cached) = cache.resolutions.borrow().get(&key).cloned() {
9859 return cached;
9860 }
9861 let resolved = enclosing_lexical_scope_components_with_unresolved_owner(
9862 node,
9863 analyzer,
9864 visibility,
9865 file,
9866 source,
9867 allow_structured_unresolved_owner,
9868 ignore_function_owner,
9869 orphaned,
9870 );
9871 cache.resolutions.borrow_mut().insert(key, resolved.clone());
9872 resolved
9873}
9874
9875fn lexical_scope_cache_anchor(node: Node<'_>) -> (usize, usize) {
9876 let mut current = node;
9877 loop {
9878 if matches!(
9879 current.kind(),
9880 "function_definition"
9881 | "class_specifier"
9882 | "struct_specifier"
9883 | "union_specifier"
9884 | "namespace_definition"
9885 | "translation_unit"
9886 ) {
9887 return (current.start_byte(), current.end_byte());
9888 }
9889 let Some(parent) = current.parent() else {
9890 return (current.start_byte(), current.end_byte());
9891 };
9892 current = parent;
9893 }
9894}
9895
9896#[allow(clippy::too_many_arguments)]
9897fn enclosing_lexical_scope_components_with_unresolved_owner(
9898 node: Node<'_>,
9899 analyzer: &CppGraphSource<'_>,
9900 visibility: &VisibilityIndex<'_>,
9901 file: &ProjectFile,
9902 source: &str,
9903 allow_structured_unresolved_owner: bool,
9904 ignore_function_owner: bool,
9905 orphaned: &OrphanedNamespaceScopeIndex,
9906) -> LexicalScopeResolution {
9907 #[cfg(any(test, feature = "test-support"))]
9908 LEXICAL_SCOPE_RECONSTRUCTIONS_FOR_TEST.with(|count| count.set(count.get() + 1));
9909 let mut namespaces = Vec::new();
9915 let mut classes = Vec::new();
9916 let mut function_definition = None;
9917 let mut displaced_class_scope = false;
9918 let mut current = node.parent();
9919 while let Some(parent) = current {
9920 match parent.kind() {
9921 "namespace_definition" => {
9922 if let Some(name) = parent.child_by_field_name("name") {
9923 let mut components = Vec::new();
9924 if append_cpp_name_components(name, source, &mut components).is_some() {
9925 namespaces.push((
9926 parent.start_byte(),
9927 components,
9928 namespace_definition_has_real_braces(parent),
9929 ));
9930 }
9931 }
9932 }
9933 "class_specifier" | "struct_specifier" | "union_specifier" => {
9934 if let Some(name) = parent.child_by_field_name("name") {
9935 let mut components = Vec::new();
9936 if append_cpp_name_components(name, source, &mut components).is_some() {
9937 classes.push(components);
9938 }
9939 }
9940 }
9941 "function_definition" => {
9942 if function_definition.is_none() {
9943 function_definition = Some(parent);
9944 }
9945 displaced_class_scope = displaced_class_scope
9946 || parent.child_by_field_name("type").is_some_and(|type_node| {
9947 matches!(
9948 type_node.kind(),
9949 "class_specifier" | "struct_specifier" | "union_specifier"
9950 )
9951 })
9952 || is_malformed_wrapper_function_definition(parent);
9953 }
9954 _ => {}
9955 }
9956 current = parent.parent();
9957 }
9958 namespaces.reverse();
9959 let namespace = orphaned.restore_enclosing_namespaces(namespaces, node.start_byte());
9962 let mut scope = namespace.clone();
9963 let has_qualified_function_owner = function_definition
9968 .filter(|function| !is_malformed_wrapper_function_definition(*function))
9969 .and_then(function_definition_owner_lookup_node)
9970 .is_some_and(|owner| {
9971 is_structurally_qualified(owner) && !is_macro_decorated_function_owner(owner)
9972 });
9973 let indexed_scope = displaced_class_scope
9974 .then(|| {
9975 indexed_structural_class_scope(visibility, file, node, source)
9976 .or_else(|| indexed_enclosing_owner_scope(analyzer, visibility, file, node))
9977 })
9978 .flatten()
9979 .or_else(|| {
9980 (has_qualified_function_owner && function_definition.is_some())
9987 .then(|| indexed_enclosing_owner_scope(analyzer, visibility, file, node))
9988 .flatten()
9989 .filter(|indexed| {
9990 qualified_owner_scope_is_recoverable(
9991 indexed,
9992 &namespace,
9993 &classes,
9994 function_definition
9995 .and_then(function_definition_owner_lookup_node)
9996 .and_then(|owner| qualified_callable_owner_components(owner, source))
9997 .map(|(components, _)| components),
9998 )
9999 })
10000 })
10001 .or_else(|| {
10002 indexed_structural_class_scope(visibility, file, node, source).or_else(|| {
10010 indexed_enclosing_owner_scope(analyzer, visibility, file, node).filter(|indexed| {
10011 qualified_owner_scope_is_recoverable(indexed, &namespace, &classes, None)
10012 })
10013 })
10014 })
10015 .or_else(|| {
10016 (classes.is_empty() && function_definition.is_some() && !has_qualified_function_owner)
10020 .then(|| indexed_enclosing_lexical_scope(analyzer, file, node))
10021 .flatten()
10022 .filter(|indexed| indexed.len() > namespace.len())
10023 });
10024 if let Some(indexed_scope) = indexed_scope.as_ref() {
10025 scope = indexed_scope.clone();
10030 classes.clear();
10031 }
10032
10033 if !ignore_function_owner
10034 && has_qualified_function_owner
10035 && let Some(function) = function_definition.and_then(function_definition_owner_lookup_node)
10036 {
10037 let Some((owner, global)) = qualified_callable_owner_components(function, source) else {
10038 return LexicalScopeResolution::Missing;
10039 };
10040 let imports = visibility.ordinary_type_import_cell(file);
10046 let owner_resolution = resolve_type_components_lexically_at_scoped(
10047 function,
10048 &owner,
10049 global,
10050 analyzer,
10051 visibility,
10052 &imports,
10053 file,
10054 source,
10055 None,
10056 false,
10057 false,
10058 false,
10059 namespace.clone(),
10060 );
10061 match owner_resolution {
10062 LexicalTypeResolution::Resolved {
10063 unit, components, ..
10064 } if is_indexed_class_owner(analyzer, &unit) => {
10065 scope = components;
10066 classes.clear();
10067 }
10068 LexicalTypeResolution::Ambiguous => return LexicalScopeResolution::Ambiguous,
10069 LexicalTypeResolution::Resolved { .. } | LexicalTypeResolution::Missing => {
10070 match visibility
10071 .resolve_type_components_lexically(analyzer, file, &owner, global, &scope)
10072 {
10073 LexicalTypeResolution::Resolved { components, .. } => scope = components,
10074 LexicalTypeResolution::Ambiguous => return LexicalScopeResolution::Ambiguous,
10075 LexicalTypeResolution::Missing if allow_structured_unresolved_owner => {
10076 if let Some(indexed) = indexed_scope.as_ref().filter(|indexed| {
10077 qualified_owner_scope_is_recoverable(
10078 indexed,
10079 &namespace,
10080 &classes,
10081 Some(owner.clone()),
10082 )
10083 }) {
10084 scope = indexed.clone();
10085 } else {
10086 scope = if global || owner.starts_with(&namespace) {
10087 owner
10088 } else {
10089 let mut relative = namespace;
10090 relative.extend(owner);
10091 relative
10092 };
10093 }
10094 }
10095 LexicalTypeResolution::Missing => {
10096 match indexed_enclosing_owner_scope(analyzer, visibility, file, node)
10106 .or_else(|| {
10107 indexed_namespace_qualified_scope(
10108 analyzer, visibility, file, node, &owner,
10109 )
10110 }) {
10111 Some(indexed) => scope = indexed,
10112 None => return LexicalScopeResolution::Missing,
10113 }
10114 }
10115 }
10116 }
10117 }
10118 }
10119
10120 classes.reverse();
10121 scope.extend(classes.into_iter().flatten());
10122 LexicalScopeResolution::Resolved(scope)
10123}
10124
10125fn has_recovered_class_shape_ancestor(node: Node<'_>) -> bool {
10126 let mut current = node.parent();
10127 while let Some(parent) = current {
10128 if parent.kind() == "function_definition"
10129 && parent.child_by_field_name("type").is_some_and(|type_node| {
10130 matches!(
10131 type_node.kind(),
10132 "class_specifier" | "struct_specifier" | "union_specifier"
10133 )
10134 })
10135 {
10136 return true;
10137 }
10138 current = parent.parent();
10139 }
10140 false
10141}
10142
10143fn has_malformed_wrapper_function_definition_ancestor(node: Node<'_>) -> bool {
10144 let mut current = node.parent();
10145 while let Some(parent) = current {
10146 if parent.kind() == "function_definition"
10147 && is_malformed_wrapper_function_definition(parent)
10148 {
10149 return true;
10150 }
10151 current = parent.parent();
10152 }
10153 false
10154}
10155
10156pub fn is_malformed_wrapper_function_definition(node: Node<'_>) -> bool {
10158 node.has_error()
10159 && node
10160 .child_by_field_name("declarator")
10161 .is_some_and(|declarator| {
10162 declarator.kind() != "function_declarator"
10163 && first_descendant_of_kind(declarator, "function_declarator").is_none()
10164 })
10165}
10166
10167fn is_macro_decorated_function_owner(node: Node<'_>) -> bool {
10173 node.child_by_field_name("scope")
10174 .and_then(|scope| recovered_macro_decorated_type_node(scope))
10175 .is_some()
10176}
10177
10178fn indexed_structural_class_scope(
10179 visibility: &VisibilityIndex<'_>,
10180 file: &ProjectFile,
10181 node: Node<'_>,
10182 source: &str,
10183) -> Option<Vec<String>> {
10184 let mut current = node.parent();
10185 while let Some(parent) = current {
10186 if matches!(
10187 parent.kind(),
10188 "class_specifier" | "struct_specifier" | "union_specifier"
10189 ) {
10190 return visibility.indexed_structural_class_scope(file, parent, source);
10191 }
10192 current = parent.parent();
10193 }
10194 None
10195}
10196
10197fn qualified_owner_scope_is_recoverable(
10208 indexed: &[String],
10209 namespace: &[String],
10210 classes: &[Vec<String>],
10211 qualified_owner: Option<Vec<String>>,
10212) -> bool {
10213 if let Some(owner) = qualified_owner {
10214 if indexed.len() <= owner.len() || !indexed.ends_with(&owner) {
10215 return false;
10216 }
10217 if namespace.is_empty() {
10223 return true;
10224 }
10225 if indexed.len() <= namespace.len() {
10226 return false;
10227 }
10228 return super::cpp_namespace_path_is_ordered_subsequence(namespace, indexed);
10229 }
10230 let class_components = classes.iter().flatten().cloned().collect::<Vec<_>>();
10231 if !class_components.is_empty() {
10232 return indexed.len() > class_components.len() && indexed.ends_with(&class_components);
10233 }
10234 if namespace.is_empty() || indexed.len() <= namespace.len() {
10235 return false;
10236 }
10237 super::cpp_namespace_path_is_ordered_subsequence(namespace, indexed)
10238}
10239
10240fn is_indexed_class_owner(analyzer: &CppGraphSource<'_>, unit: &CodeUnit) -> bool {
10243 unit.is_class()
10244 && !analyzer
10245 .type_alias_provider()
10246 .is_some_and(|provider| provider.is_type_alias(unit))
10247}
10248
10249fn indexed_enclosing_owner_scope(
10263 analyzer: &CppGraphSource<'_>,
10264 visibility: &VisibilityIndex<'_>,
10265 file: &ProjectFile,
10266 node: Node<'_>,
10267) -> Option<Vec<String>> {
10268 visibility.indexed_enclosing_owner_scope(analyzer, file, node)
10269}
10270
10271fn indexed_namespace_qualified_scope(
10288 analyzer: &CppGraphSource<'_>,
10289 visibility: &VisibilityIndex<'_>,
10290 file: &ProjectFile,
10291 node: Node<'_>,
10292 owner: &[String],
10293) -> Option<Vec<String>> {
10294 let name = owner.last().expect("a qualified owner has one component");
10295 if !visibility
10296 .visible_identifier_candidates(file, name)
10297 .any(|unit| unit.is_module())
10298 {
10299 return None;
10300 }
10301 let indexed = indexed_enclosing_lexical_scope(analyzer, file, node)?;
10302 indexed.ends_with(owner).then_some(indexed)
10303}
10304
10305fn cached_indexed_enclosing_class_owner(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
10306 let start = enclosing_context(node, ctx).enclosing?;
10307 brokk_bifrost_core::analyzer::usages::common::enclosing_owner_chain(start, |unit| {
10308 ctx.analyzer.parent_of(unit)
10309 })
10310 .find(|unit| is_indexed_class_owner(&ctx.analyzer, unit))
10311}
10312
10313pub fn resolve_type_node_lexically(
10314 node: Node<'_>,
10315 analyzer: &CppGraphSource<'_>,
10316 visibility: &VisibilityIndex<'_>,
10317 ordinary_type_imports: &OrdinaryTypeImportCell,
10318 file: &ProjectFile,
10319 source: &str,
10320) -> LexicalTypeResolution {
10321 let Some((components, global)) = type_reference_components(node, source) else {
10322 return LexicalTypeResolution::Missing;
10323 };
10324 let resolution = resolve_type_components_lexically_at(
10325 node,
10326 &components,
10327 global,
10328 analyzer,
10329 visibility,
10330 ordinary_type_imports,
10331 file,
10332 source,
10333 );
10334 if !is_cpp_template_argument_type_leaf(node) {
10335 return resolution;
10336 }
10337
10338 let Some(indexed_scope) = indexed_enclosing_lexical_scope(analyzer, file, node) else {
10345 return resolution;
10346 };
10347 let namespace_scope = enclosing_namespace_components(node, source);
10348 if indexed_scope.len() <= namespace_scope.len() {
10349 return resolution;
10350 }
10351 let indexed = visibility.resolve_type_components_lexically(
10352 analyzer,
10353 file,
10354 &components,
10355 global,
10356 &indexed_scope,
10357 );
10358 match indexed {
10359 LexicalTypeResolution::Resolved { ref unit, .. }
10360 if !visibility
10361 .external_type_candidate_visible_in_context(analyzer, file, unit, node) =>
10362 {
10363 resolution
10364 }
10365 LexicalTypeResolution::Resolved { .. } => indexed,
10366 _ => resolution,
10367 }
10368}
10369
10370#[allow(clippy::too_many_arguments)]
10371pub fn resolve_type_node_lexically_for_target(
10372 node: Node<'_>,
10373 analyzer: &CppGraphSource<'_>,
10374 visibility: &VisibilityIndex<'_>,
10375 ordinary_type_imports: &OrdinaryTypeImportCell,
10376 file: &ProjectFile,
10377 source: &str,
10378 target: &CodeUnit,
10379 scope_cache: Option<&LexicalScopeCache>,
10380 recovered_scope: Option<&[String]>,
10381) -> LexicalTypeResolution {
10382 let Some((reference_components, global)) = type_reference_components(node, source) else {
10383 return LexicalTypeResolution::Missing;
10384 };
10385 let terminal = reference_components
10386 .last()
10387 .expect("type reference components are non-empty");
10388 if !visibility.coarse_unqualified_type_reference_may_resolve(file, terminal) {
10389 return LexicalTypeResolution::Missing;
10390 }
10391 let template_arguments = cpp_template_reference_arguments(node, source);
10392 let selects_concrete_specialization =
10393 template_arguments.is_some() && visibility.is_template_specialization(target);
10394 if !selects_concrete_specialization
10395 && !visibility.structured_type_reference_may_resolve_to_target(
10396 analyzer,
10397 file,
10398 std::slice::from_ref(terminal),
10399 false,
10400 &[],
10401 target,
10402 )
10403 {
10404 return LexicalTypeResolution::Missing;
10405 }
10406 if let Some(arguments) = template_arguments.as_ref() {
10407 let alias_resolution = if let Some(recovered_scope) = recovered_scope {
10408 resolve_type_components_lexically_at_preserving_alias_with_recovered_scope(
10409 node,
10410 &reference_components,
10411 global,
10412 analyzer,
10413 visibility,
10414 ordinary_type_imports,
10415 file,
10416 source,
10417 recovered_scope,
10418 )
10419 } else {
10420 resolve_type_components_lexically_at_preserving_alias_with_scope_cache(
10421 node,
10422 &reference_components,
10423 global,
10424 analyzer,
10425 visibility,
10426 ordinary_type_imports,
10427 file,
10428 source,
10429 scope_cache,
10430 )
10431 };
10432 return match alias_resolution {
10433 LexicalTypeResolution::Resolved {
10434 unit,
10435 components,
10436 candidates,
10437 } if visibility.template_alias_arguments_preserve_target(
10438 analyzer, file, &unit, arguments, target,
10439 ) =>
10440 {
10441 LexicalTypeResolution::Resolved {
10442 unit: target.clone(),
10443 components,
10444 candidates,
10445 }
10446 }
10447 LexicalTypeResolution::Resolved {
10448 unit,
10449 components,
10450 candidates,
10451 } => match visibility.resolve_template_arguments(file, unit.clone(), arguments) {
10452 Ok(resolved_unit) => {
10453 let target_guided = (!same_visible_symbol(&resolved_unit, target))
10454 .then(|| {
10455 target_guided_malformed_template_alias_resolution(
10456 node,
10457 analyzer,
10458 visibility,
10459 file,
10460 arguments,
10461 &reference_components,
10462 target,
10463 )
10464 })
10465 .flatten();
10466 target_guided.unwrap_or(LexicalTypeResolution::Resolved {
10467 unit: resolved_unit,
10468 components,
10469 candidates,
10470 })
10471 }
10472 Err(_) => LexicalTypeResolution::Ambiguous,
10473 },
10474 LexicalTypeResolution::Missing => {
10475 let target_preserving = if let Some(recovered_scope) = recovered_scope {
10476 resolve_type_components_lexically_at_for_target_with_recovered_scope(
10477 node,
10478 &reference_components,
10479 global,
10480 analyzer,
10481 visibility,
10482 ordinary_type_imports,
10483 file,
10484 source,
10485 target,
10486 true,
10487 recovered_scope,
10488 )
10489 } else {
10490 resolve_type_components_lexically_at_for_target_with_scope_cache(
10491 node,
10492 &reference_components,
10493 global,
10494 analyzer,
10495 visibility,
10496 ordinary_type_imports,
10497 file,
10498 source,
10499 target,
10500 true,
10501 scope_cache,
10502 )
10503 };
10504 match target_preserving {
10505 LexicalTypeResolution::Resolved {
10506 unit: _,
10507 components,
10508 candidates,
10509 } if template_reference_candidates_select_target(
10510 node,
10511 &candidates,
10512 analyzer,
10513 visibility,
10514 file,
10515 source,
10516 target,
10517 ) =>
10518 {
10519 LexicalTypeResolution::Resolved {
10520 unit: target.clone(),
10521 components,
10522 candidates,
10523 }
10524 }
10525 _ => target_guided_malformed_template_alias_resolution(
10526 node,
10527 analyzer,
10528 visibility,
10529 file,
10530 arguments,
10531 &reference_components,
10532 target,
10533 )
10534 .unwrap_or(LexicalTypeResolution::Missing),
10535 }
10536 }
10537 LexicalTypeResolution::Ambiguous => LexicalTypeResolution::Ambiguous,
10538 };
10539 }
10540 let resolution = if let Some(recovered_scope) = recovered_scope {
10541 resolve_type_components_lexically_at_for_target_with_recovered_scope(
10542 node,
10543 &reference_components,
10544 global,
10545 analyzer,
10546 visibility,
10547 ordinary_type_imports,
10548 file,
10549 source,
10550 target,
10551 true,
10552 recovered_scope,
10553 )
10554 } else {
10555 resolve_type_components_lexically_at_for_target_with_scope_cache(
10556 node,
10557 &reference_components,
10558 global,
10559 analyzer,
10560 visibility,
10561 ordinary_type_imports,
10562 file,
10563 source,
10564 target,
10565 true,
10566 scope_cache,
10567 )
10568 };
10569 let resolution = if matches!(resolution, LexicalTypeResolution::Missing) {
10570 target_guided_qualified_namespace_function_type_resolution(
10571 node,
10572 &reference_components,
10573 global,
10574 analyzer,
10575 visibility,
10576 ordinary_type_imports,
10577 file,
10578 source,
10579 target,
10580 )
10581 .unwrap_or(resolution)
10582 } else {
10583 resolution
10584 };
10585 if !is_cpp_template_argument_type_leaf(node) {
10586 return resolution;
10587 }
10588
10589 let Some(indexed_scope) = indexed_enclosing_lexical_scope(analyzer, file, node) else {
10597 return resolution;
10598 };
10599 let namespace_scope = enclosing_namespace_components(node, source);
10600 if indexed_scope.len() <= namespace_scope.len() {
10601 return resolution;
10602 }
10603 let indexed = visibility.resolve_type_components_lexically_for_target(
10604 analyzer,
10605 file,
10606 &reference_components,
10607 global,
10608 &indexed_scope,
10609 target,
10610 );
10611 match indexed {
10612 LexicalTypeResolution::Resolved {
10613 ref unit,
10614 ref candidates,
10615 ..
10616 } if (same_visible_symbol(unit, target)
10617 || candidates
10618 .iter()
10619 .any(|candidate| same_visible_symbol(candidate, target)))
10620 && visibility
10621 .external_type_candidate_visible_in_context(analyzer, file, unit, node) =>
10622 {
10623 indexed
10624 }
10625 _ => resolution,
10626 }
10627}
10628
10629#[allow(clippy::too_many_arguments)]
10639fn target_guided_qualified_namespace_function_type_resolution(
10640 node: Node<'_>,
10641 components: &[String],
10642 global: bool,
10643 analyzer: &CppGraphSource<'_>,
10644 visibility: &VisibilityIndex<'_>,
10645 ordinary_type_imports: &OrdinaryTypeImportCell,
10646 file: &ProjectFile,
10647 source: &str,
10648 target: &CodeUnit,
10649) -> Option<LexicalTypeResolution> {
10650 let function_definition = std::iter::successors(Some(node), |current| current.parent())
10651 .find(|current| current.kind() == "function_definition")?;
10652 let function = function_definition_name_node(function_definition)?;
10653 let (owner, owner_global) = qualified_callable_owner_components(function, source)?;
10654 let target_namespace = target.package_name();
10655 if target_namespace.is_empty() {
10656 return None;
10657 }
10658 let target_scope = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
10659 brokk_bifrost_core::analyzer::Language::Cpp,
10660 target_namespace,
10661 );
10662 if (owner_global && target_scope != owner) || (!owner_global && !target_scope.ends_with(&owner))
10663 {
10664 return None;
10665 }
10666
10667 let function_name = node_text(function_terminal_node(function), source);
10668 let definition_unit = canonical_callable_at_node(
10669 function_definition,
10670 analyzer,
10671 visibility,
10672 file,
10673 source,
10674 TargetKind::FreeFunction,
10675 )?;
10676 let definition_arity = cpp_callable_arity(analyzer, &definition_unit)?.total();
10677 let declaration_proves_namespace = visibility
10678 .visible_identifier_candidates(file, function_name)
10679 .filter(|candidate| {
10680 candidate.is_function()
10681 && type_owner_of(analyzer, candidate).is_none()
10682 && candidate.package_name() == target_namespace
10683 })
10684 .any(|candidate| {
10685 cpp_callable_arity(analyzer, candidate)
10686 .is_none_or(|known| known.accepts(definition_arity))
10687 });
10688 if !declaration_proves_namespace {
10689 return None;
10690 }
10691
10692 let resolution = resolve_type_components_lexically_at_scoped(
10693 node,
10694 components,
10695 global,
10696 analyzer,
10697 visibility,
10698 ordinary_type_imports,
10699 file,
10700 source,
10701 Some(target),
10702 true,
10703 false,
10704 false,
10705 target_scope,
10706 );
10707 match &resolution {
10708 LexicalTypeResolution::Resolved {
10709 unit, candidates, ..
10710 } if (same_visible_symbol(unit, target)
10711 || candidates
10712 .iter()
10713 .any(|candidate| same_visible_symbol(candidate, target)))
10714 && visibility
10715 .external_type_candidate_visible_in_context(analyzer, file, unit, node) =>
10716 {
10717 Some(resolution)
10718 }
10719 LexicalTypeResolution::Resolved { .. }
10720 | LexicalTypeResolution::Ambiguous
10721 | LexicalTypeResolution::Missing => None,
10722 }
10723}
10724
10725#[allow(clippy::too_many_arguments)]
10726fn target_guided_malformed_template_alias_resolution(
10727 node: Node<'_>,
10728 analyzer: &CppGraphSource<'_>,
10729 visibility: &VisibilityIndex<'_>,
10730 file: &ProjectFile,
10731 arguments: &[brokk_bifrost_core::analyzer::model::CppTemplateExpression],
10732 components: &[String],
10733 target: &CodeUnit,
10734) -> Option<LexicalTypeResolution> {
10735 if components.len() != 1 || !has_malformed_wrapper_function_definition_ancestor(node) {
10736 return None;
10737 }
10738
10739 let identifier = &components[0];
10740 let namespace =
10741 visibility.target_preserving_reference_namespace(analyzer, file, identifier, target)?;
10742 let namespace_name = namespace.join("::");
10743 let candidates = visibility
10744 .visible_identifier_candidates(file, identifier)
10745 .filter(|candidate| {
10746 cpp_namespace_for(candidate).unwrap_or_default() == namespace_name
10747 && visibility.type_candidate_may_be_visible_before_reference(
10748 analyzer,
10749 file,
10750 candidate,
10751 node.start_byte(),
10752 )
10753 })
10754 .cloned()
10755 .collect::<Vec<_>>();
10756 let first = candidates.first()?;
10757 if !candidates
10758 .iter()
10759 .all(|candidate| same_logical_symbol(first, candidate))
10760 || !candidates.iter().all(|candidate| {
10761 visibility.template_alias_arguments_preserve_target(
10762 analyzer, file, candidate, arguments, target,
10763 )
10764 })
10765 {
10766 return None;
10767 }
10768
10769 let mut resolved_components = namespace;
10770 resolved_components.push(identifier.clone());
10771 Some(LexicalTypeResolution::Resolved {
10772 unit: target.clone(),
10773 components: resolved_components,
10774 candidates,
10775 })
10776}
10777
10778fn resolve_type_node_lexically_for_target_without_visibility(
10779 node: Node<'_>,
10780 analyzer: &CppGraphSource<'_>,
10781 visibility: &VisibilityIndex<'_>,
10782 file: &ProjectFile,
10783 source: &str,
10784 target: &CodeUnit,
10785) -> LexicalTypeResolution {
10786 let Some((components, global)) = type_reference_components(node, source) else {
10787 return LexicalTypeResolution::Missing;
10788 };
10789 let lexical_scope = match enclosing_lexical_scope_components_with_unresolved_owner(
10790 node,
10791 analyzer,
10792 visibility,
10793 file,
10794 source,
10795 true,
10796 recovered_macro_decorated_declarator_type(node)
10797 == Some(RecoveredDeclaratorTypeContext::FunctionDefinition),
10798 &orphaned_namespace_scopes(visibility, file),
10799 ) {
10800 LexicalScopeResolution::Resolved(scope) => scope,
10801 LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
10802 LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
10803 };
10804 visibility.resolve_type_components_lexically_for_target(
10805 analyzer,
10806 file,
10807 &components,
10808 global,
10809 &lexical_scope,
10810 target,
10811 )
10812}
10813
10814fn type_node_has_exact_target_identity_without_visibility(
10815 node: Node<'_>,
10816 analyzer: &CppGraphSource<'_>,
10817 visibility: &VisibilityIndex<'_>,
10818 file: &ProjectFile,
10819 source: &str,
10820 target: &CodeUnit,
10821) -> bool {
10822 let Some((components, global)) = type_reference_components(node, source) else {
10823 return false;
10824 };
10825 let LexicalScopeResolution::Resolved(lexical_scope) =
10826 enclosing_lexical_scope_components_with_unresolved_owner(
10827 node,
10828 analyzer,
10829 visibility,
10830 file,
10831 source,
10832 true,
10833 recovered_macro_decorated_declarator_type(node)
10834 == Some(RecoveredDeclaratorTypeContext::FunctionDefinition),
10835 &orphaned_namespace_scopes(visibility, file),
10836 )
10837 else {
10838 return false;
10839 };
10840 let target_name = cpp_name_for(target);
10841 lexical_component_tiers(&components, global, &lexical_scope)
10842 .any(|qualified| qualified.join("::") == target_name)
10843}
10844
10845pub fn resolve_using_enum_declaration_owner(
10846 node: Node<'_>,
10847 analyzer: &CppGraphSource<'_>,
10848 visibility: &VisibilityIndex<'_>,
10849 ordinary_type_imports: &OrdinaryTypeImportCell,
10850 file: &ProjectFile,
10851 source: &str,
10852) -> LexicalTypeResolution {
10853 let Some(type_node) = using_enum_declaration_type_node(node) else {
10854 return LexicalTypeResolution::Missing;
10855 };
10856 let mut components = Vec::new();
10857 if append_cpp_name_components(type_node, source, &mut components).is_none()
10858 || components.is_empty()
10859 {
10860 return LexicalTypeResolution::Missing;
10861 }
10862 resolve_type_components_lexically_at(
10863 type_node,
10864 &components,
10865 is_globally_qualified_cpp_name(type_node),
10866 analyzer,
10867 visibility,
10868 ordinary_type_imports,
10869 file,
10870 source,
10871 )
10872}
10873
10874pub fn resolve_ordinary_using_declaration_owner(
10875 node: Node<'_>,
10876 analyzer: &CppGraphSource<'_>,
10877 visibility: &VisibilityIndex<'_>,
10878 file: &ProjectFile,
10879 source: &str,
10880) -> LexicalTypeResolution {
10881 let Some(type_node) = ordinary_using_declaration_type_node(node) else {
10882 return LexicalTypeResolution::Missing;
10883 };
10884 let mut components = Vec::new();
10885 if append_cpp_name_components(type_node, source, &mut components).is_none()
10886 || components.len() < 2
10887 {
10888 return LexicalTypeResolution::Missing;
10889 }
10890 let lexical_scope =
10891 match enclosing_lexical_scope_components(type_node, analyzer, visibility, file, source) {
10892 LexicalScopeResolution::Resolved(scope) => scope,
10893 LexicalScopeResolution::Ambiguous => return LexicalTypeResolution::Ambiguous,
10894 LexicalScopeResolution::Missing => return LexicalTypeResolution::Missing,
10895 };
10896 visibility.resolve_type_components_lexically(
10897 analyzer,
10898 file,
10899 &components,
10900 is_globally_qualified_cpp_name(type_node),
10901 &lexical_scope,
10902 )
10903}
10904
10905pub fn using_enum_declaration_type_node(node: Node<'_>) -> Option<Node<'_>> {
10906 (node.kind() == "using_declaration"
10907 && (0..node.child_count()).any(|index| {
10908 node.child(index)
10909 .is_some_and(|child| child.kind() == "enum")
10910 }))
10911 .then(|| node.named_child(0))
10912 .flatten()
10913}
10914
10915pub fn ordinary_using_declaration_type_node(node: Node<'_>) -> Option<Node<'_>> {
10916 (node.kind() == "using_declaration"
10917 && using_enum_declaration_type_node(node).is_none()
10918 && using_namespace_directive_name_node(node).is_none())
10919 .then(|| node.named_child(0))
10920 .flatten()
10921}
10922
10923fn recovered_macro_using_declaration_type_node<'tree>(
10930 node: Node<'tree>,
10931 source: &str,
10932) -> Option<(Node<'tree>, bool)> {
10933 if node.kind() != "declaration" {
10934 return None;
10935 }
10936 let macro_type = node.child_by_field_name("type")?;
10937 if macro_type.kind() != "type_identifier"
10938 || !cpp_export_macro_token(node_text(macro_type, source))
10939 {
10940 return None;
10941 }
10942 let declarator = node.child_by_field_name("declarator")?;
10943 if declarator.kind() != "qualified_identifier" {
10944 return None;
10945 }
10946 let scope = declarator.child_by_field_name("scope")?;
10947 if scope.kind() != "namespace_identifier" || node_text(scope, source) != "using" {
10948 return None;
10949 }
10950 let target = declarator.child_by_field_name("name")?;
10951 let mut components = Vec::new();
10952 append_cpp_name_components(target, source, &mut components)?;
10953 (components.len() >= 2).then_some((target, is_globally_qualified_cpp_name(target)))
10954}
10955
10956fn using_namespace_directive_name_node(node: Node<'_>) -> Option<Node<'_>> {
10957 let is_directive = node.kind() == "using_directive"
10958 || (node.kind() == "using_declaration"
10959 && (0..node.child_count()).any(|index| {
10960 node.child(index)
10961 .is_some_and(|child| child.kind() == "namespace")
10962 }));
10963 if !is_directive {
10964 return None;
10965 }
10966 node.child_by_field_name("name")
10967 .or_else(|| node.named_child(node.named_child_count().checked_sub(1)?))
10968}
10969
10970fn using_named_scope(node: Node<'_>, source: &str) -> Option<Vec<String>> {
10971 let mut current = node.parent();
10972 while let Some(parent) = current {
10973 if matches!(
10974 parent.kind(),
10975 "compound_statement"
10976 | "function_definition"
10977 | "lambda_expression"
10978 | "for_statement"
10979 | "while_statement"
10980 | "if_statement"
10981 | "class_specifier"
10982 | "struct_specifier"
10983 | "union_specifier"
10984 ) {
10985 return None;
10986 }
10987 current = parent.parent();
10988 }
10989 Some(enclosing_namespace_components(node, source))
10990}
10991
10992fn ordinary_using_scope(node: Node<'_>) -> Option<(usize, usize, usize, bool)> {
10993 let mut current = node.parent();
10994 while let Some(scope) = current {
10995 if matches!(
10996 scope.kind(),
10997 "compound_statement"
10998 | "declaration_list"
10999 | "field_declaration_list"
11000 | "translation_unit"
11001 ) {
11002 let mut depth = 0;
11003 let mut ancestor = scope.parent();
11004 while let Some(parent) = ancestor {
11005 depth += 1;
11006 ancestor = parent.parent();
11007 }
11008 return Some((
11009 scope.start_byte(),
11010 scope.end_byte(),
11011 depth,
11012 scope.kind() == "compound_statement",
11013 ));
11014 }
11015 current = scope.parent();
11016 }
11017 None
11018}
11019
11020pub fn build_source_using_index(
11027 cpp: &dyn CppSource,
11028 token: QueryToken<'_>,
11029 file: &ProjectFile,
11030) -> SourceUsingIndex {
11031 let Some(prepared) = cpp.prepared_syntax(token, file) else {
11032 return SourceUsingIndex::default();
11033 };
11034 collect_source_using_index(cpp, file, prepared.tree().root_node(), prepared.source())
11035}
11036
11037fn collect_source_using_index(
11038 cpp: &dyn CppSource,
11039 source_file: &ProjectFile,
11040 root: Node<'_>,
11041 source: &str,
11042) -> SourceUsingIndex {
11043 #[cfg(not(any(test, feature = "test-support")))]
11044 let _ = cpp;
11045 let mut index = SourceUsingIndex::default();
11046 let orphaned_namespaces = collect_orphaned_namespace_envelopes(root, source);
11047 let mut stack = vec![root];
11048 while let Some(node) = stack.pop() {
11049 let target = match node.kind() {
11050 "using_directive" | "using_declaration" => {
11051 if let Some(namespace_node) = using_namespace_directive_name_node(node) {
11052 let mut namespace_components = Vec::new();
11053 append_cpp_name_components(namespace_node, source, &mut namespace_components)
11054 .map(|_| EffectiveUsingTarget::Namespace {
11055 namespace_components,
11056 global: is_globally_qualified_cpp_name(namespace_node),
11057 })
11058 } else if let Some(type_node) = ordinary_using_declaration_type_node(node) {
11059 let mut target_components = Vec::new();
11060 (append_cpp_name_components(type_node, source, &mut target_components)
11061 .is_some()
11062 && target_components.len() >= 2)
11063 .then(|| EffectiveUsingTarget::Ordinary {
11064 name: target_components
11065 .last()
11066 .expect("ordinary using has a terminal component")
11067 .clone(),
11068 target_components,
11069 global: is_globally_qualified_cpp_name(type_node),
11070 })
11071 } else {
11072 None
11073 }
11074 }
11075 "declaration" => recovered_macro_using_declaration_type_node(node, source).and_then(
11076 |(type_node, global)| {
11077 let mut target_components = Vec::new();
11078 (append_cpp_name_components(type_node, source, &mut target_components)
11079 .is_some()
11080 && target_components.len() >= 2)
11081 .then(|| EffectiveUsingTarget::Ordinary {
11082 name: target_components
11083 .last()
11084 .expect("recovered ordinary using has a terminal component")
11085 .clone(),
11086 target_components,
11087 global,
11088 })
11089 },
11090 ),
11091 _ => None,
11092 };
11093 if let Some(target) = target {
11094 #[cfg(any(test, feature = "test-support"))]
11100 cpp.record_using_guard_context_inspection_for_test();
11101 let required_guards = if callable_preprocessor_context_is_visible(node, source) {
11102 Some(HashSet::default())
11103 } else {
11104 preprocessor_guard_environment(node, source)
11105 };
11106 let Some(required_guards) = required_guards else {
11107 let mut cursor = node.walk();
11108 stack.extend(node.children(&mut cursor));
11109 continue;
11110 };
11111 if let Some((scope_start, scope_end, scope_depth, block_scope)) =
11112 ordinary_using_scope(node)
11113 {
11114 let declaration_namespace = enclosing_namespace_components(node, source);
11115 let declaration_namespace = if declaration_namespace.is_empty() {
11116 recovered_orphaned_namespace_components(node, source, &orphaned_namespaces)
11117 .unwrap_or(declaration_namespace)
11118 } else {
11119 declaration_namespace
11120 };
11121 let namespace_scope = using_named_scope(node, source);
11122 let lexical_depth = declaration_namespace.len();
11123 let binding = OrdinaryTypeImport {
11124 target,
11125 source: source_file.clone(),
11126 declaration_byte: node.end_byte(),
11127 scope_start,
11128 scope_end,
11129 scope_depth,
11130 block_scope,
11131 lexical_depth,
11132 declaration_namespace,
11133 namespace_scope,
11134 resolved_target_components: None,
11135 required_guards,
11136 };
11137 match &binding.target {
11138 EffectiveUsingTarget::Ordinary { name, .. } => index
11139 .ordinary_by_name
11140 .entry(name.clone())
11141 .or_default()
11142 .push(binding),
11143 EffectiveUsingTarget::Namespace { .. } => index.directives.push(binding),
11144 }
11145 }
11146 }
11147 let mut cursor = node.walk();
11148 stack.extend(node.children(&mut cursor));
11149 }
11150 index
11151}
11152
11153struct OrphanedNamespaceEnvelope {
11154 body_end: usize,
11155 components: Vec<String>,
11156 class_names: HashSet<String>,
11157}
11158
11159fn collect_orphaned_namespace_envelopes(
11166 root: Node<'_>,
11167 source: &str,
11168) -> Vec<OrphanedNamespaceEnvelope> {
11169 let mut envelopes = Vec::new();
11170 let mut stack = vec![root];
11171 while let Some(current) = stack.pop() {
11172 if current.kind() == "namespace_definition"
11173 && let Some(body) = current.child_by_field_name("body")
11174 && current.end_byte() == body.end_byte()
11175 && let Some(name) = current.child_by_field_name("name")
11176 {
11177 let mut components = enclosing_namespace_components(current, source);
11178 if append_cpp_name_components(name, source, &mut components).is_some()
11179 && !components.is_empty()
11180 {
11181 let mut class_names = HashSet::default();
11182 let mut body_stack = vec![body];
11183 while let Some(node) = body_stack.pop() {
11184 if let Some(name) = orphaned_class_definition_name(node, source) {
11185 class_names.insert(name);
11186 }
11187 let mut cursor = node.walk();
11188 if node.kind() == "ERROR" {
11189 body_stack.extend(node.children(&mut cursor));
11190 } else {
11191 body_stack.extend(node.named_children(&mut cursor));
11192 }
11193 }
11194 envelopes.push(OrphanedNamespaceEnvelope {
11195 body_end: body.end_byte(),
11196 components,
11197 class_names,
11198 });
11199 }
11200 }
11201 let mut cursor = current.walk();
11202 stack.extend(current.named_children(&mut cursor));
11203 }
11204 envelopes
11205}
11206
11207fn orphaned_class_definition_name(node: Node<'_>, source: &str) -> Option<String> {
11208 if matches!(
11209 node.kind(),
11210 "class_specifier" | "struct_specifier" | "union_specifier"
11211 ) {
11212 let body = node.child_by_field_name("body")?;
11213 let name = node.child_by_field_name("name")?;
11214 return (!name.is_missing() && !body.is_missing())
11215 .then(|| node_text(name, source).to_string());
11216 }
11217 if node.kind() != "ERROR" {
11218 return None;
11219 }
11220
11221 for index in 0..node.child_count() {
11227 let Some(keyword) = node.child(index) else {
11228 continue;
11229 };
11230 if !matches!(keyword.kind(), "class" | "struct" | "union") {
11231 continue;
11232 }
11233 let mut name = None;
11234 for next_index in (index + 1)..node.child_count() {
11235 let Some(next) = node.child(next_index) else {
11236 continue;
11237 };
11238 if next.kind() == ";" {
11239 break;
11240 }
11241 if next.kind() == "{" {
11242 return name
11243 .filter(|name_node: &Node<'_>| !name_node.is_missing())
11244 .map(|name_node| node_text(name_node, source).to_string());
11245 }
11246 if name.is_none() && matches!(next.kind(), "identifier" | "type_identifier") {
11247 name = Some(next);
11248 }
11249 }
11250 }
11251 None
11252}
11253
11254fn recovered_orphaned_namespace_components(
11255 node: Node<'_>,
11256 source: &str,
11257 envelopes: &[OrphanedNamespaceEnvelope],
11258) -> Option<Vec<String>> {
11259 let owner_name = orphaned_using_owner_name(node, source)?;
11260 envelopes
11261 .iter()
11262 .filter(|envelope| {
11263 envelope.body_end <= node.start_byte() && envelope.class_names.contains(&owner_name)
11264 })
11265 .max_by_key(|envelope| envelope.body_end)
11266 .map(|envelope| envelope.components.clone())
11267}
11268
11269fn orphaned_using_owner_name(node: Node<'_>, source: &str) -> Option<String> {
11270 let function = std::iter::successors(node.parent(), |current| current.parent())
11271 .find(|current| current.kind() == "function_definition")?;
11272 let owner = function_definition_owner_lookup_node(function)?;
11273 let scope = owner.child_by_field_name("scope")?;
11274 let mut components = Vec::new();
11275 append_cpp_name_components(scope, source, &mut components)?;
11276 if components.len() != 1 {
11283 return None;
11284 }
11285 components.pop()
11286}
11287
11288fn build_project_using_index(visibility: &VisibilityIndex<'_>) -> ProjectUsingIndex {
11289 let started = Instant::now();
11290 let report_stats = std::env::var_os("BIFROST_CPP_VISIBILITY_STATS").is_some();
11291 let source_files = visibility.all_visible_source_files();
11292 if report_stats {
11293 eprintln!(
11294 "BIFROST_CPP_USING_INDEX_STATS status=started source_files={}",
11295 source_files.len()
11296 );
11297 }
11298 let mut project = ProjectUsingIndex::default();
11299 let mut ordinary_bindings = 0usize;
11300 for source_file in &source_files {
11301 let source_index = visibility
11305 .cpp()
11306 .source_using_index(visibility.token(), source_file);
11307 for (name, bindings) in &source_index.ordinary_by_name {
11308 ordinary_bindings += bindings.len();
11309 project
11310 .ordinary_by_name
11311 .entry(name.clone())
11312 .or_default()
11313 .extend(bindings.iter().cloned());
11314 }
11315 project
11316 .directives
11317 .extend(source_index.directives.iter().cloned());
11318 }
11319 if report_stats {
11320 eprintln!(
11321 "BIFROST_CPP_USING_INDEX_STATS status=completed source_files={} ordinary_names={} ordinary_bindings={} directives={} elapsed_ms={}",
11322 source_files.len(),
11323 project.ordinary_by_name.len(),
11324 ordinary_bindings,
11325 project.directives.len(),
11326 started.elapsed().as_millis(),
11327 );
11328 }
11329 project
11330}
11331
11332fn project_using_index<'a>(visibility: &'a VisibilityIndex<'_>) -> &'a ProjectUsingIndex {
11333 visibility.project_using_index(|| build_project_using_index(visibility))
11334}
11335
11336pub fn prewarm_project_using_index(visibility: &VisibilityIndex<'_>) {
11342 let _ = project_using_index(visibility);
11343}
11344
11345fn effective_using_target_tiers(binding: &OrdinaryTypeImport) -> Vec<Vec<String>> {
11346 let (components, global) = match &binding.target {
11347 EffectiveUsingTarget::Ordinary {
11348 target_components,
11349 global,
11350 ..
11351 } => (target_components, *global),
11352 EffectiveUsingTarget::Namespace {
11353 namespace_components,
11354 global,
11355 } => (namespace_components, *global),
11356 };
11357 lexical_component_tiers(components, global, &binding.declaration_namespace).collect()
11358}
11359
11360fn using_binding_target_components_for_name(
11361 binding: &OrdinaryTypeImport,
11362 project: &ProjectUsingIndex,
11363 visibility: &VisibilityIndex<'_>,
11364 file: &ProjectFile,
11365 name: &str,
11366) -> Option<Vec<String>> {
11367 let cpp_source = CppGraphSource::from_source(visibility.cpp(), visibility.token());
11370 let visible_candidates = visibility
11371 .visible_identifier_candidates(file, name)
11372 .filter(|candidate| {
11373 candidate.is_class()
11374 || declared_type_alias(&cpp_source, candidate)
11375 || (candidate.is_function() && type_owner_of(&cpp_source, candidate).is_none())
11376 })
11377 .collect::<Vec<_>>();
11378 if visible_candidates.is_empty() {
11379 return None;
11380 }
11381 match &binding.target {
11382 EffectiveUsingTarget::Ordinary {
11383 name: imported_name,
11384 ..
11385 } if imported_name == name => {
11386 effective_using_target_tiers(binding)
11387 .into_iter()
11388 .find(|qualified| {
11389 let qualified_name = qualified.join("::");
11390 visible_candidates
11391 .iter()
11392 .any(|candidate| cpp_name_for(candidate) == qualified_name)
11393 })
11394 }
11395 EffectiveUsingTarget::Namespace { .. } => {
11396 visibility.note_using_namespace_lookup_for_test();
11397 let target_tiers = effective_using_target_tiers(binding);
11398 let resolved = target_tiers
11399 .iter()
11400 .find(|namespace_components| {
11401 let namespace = namespace_components.join("::");
11402 visible_candidates.iter().any(|candidate| {
11403 visibility.note_using_name_candidate_inspection_for_test();
11404 cpp_namespace_for(candidate).is_some_and(|candidate_namespace| {
11405 candidate_namespace == namespace
11406 || candidate_namespace.starts_with(&format!("{namespace}::"))
11407 })
11408 }) || project.directives.iter().any(|candidate| {
11409 candidate.namespace_scope.as_deref()
11410 == Some(namespace_components.as_slice())
11411 }) || project
11412 .ordinary_by_name
11413 .values()
11414 .flatten()
11415 .any(|candidate| {
11416 candidate.namespace_scope.as_deref()
11417 == Some(namespace_components.as_slice())
11418 })
11419 })
11420 .cloned();
11421 resolved.or_else(|| {
11422 (target_tiers.len() == 1)
11428 .then(|| target_tiers.into_iter().next())
11429 .flatten()
11430 })
11431 }
11432 EffectiveUsingTarget::Ordinary { .. } => None,
11433 }
11434}
11435
11436fn include_node_for_activation(root: Node<'_>, activation: usize) -> Option<Node<'_>> {
11437 let start = activation.checked_sub(1)?;
11438 let mut node = root.descendant_for_byte_range(start, activation)?;
11439 while node.kind() != "preproc_include" {
11440 node = node.parent()?;
11441 }
11442 Some(node)
11443}
11444
11445fn project_using_bindings(
11446 binding: OrdinaryTypeImport,
11447 visibility: &VisibilityIndex<'_>,
11448 file: &ProjectFile,
11449 root: Node<'_>,
11450 source: &str,
11451) -> Vec<OrdinaryTypeImport> {
11452 if binding.source == *file {
11453 return vec![binding];
11454 }
11455 if !visibility.source_is_visible(file, &binding.source) || binding.namespace_scope.is_none() {
11456 return Vec::new();
11457 }
11458 visibility.note_using_donor_activation_for_test();
11459 let Some(prepared) = visibility.cpp().prepared_syntax(visibility.token(), file) else {
11460 return Vec::new();
11461 };
11462 let projections = visibility
11463 .include_activation_for_source(visibility.cpp(), file, prepared.as_ref(), &binding.source)
11464 .map_or_else(
11465 || {
11466 visibility.conditional_include_projections_for_source(
11467 file,
11468 prepared.as_ref(),
11469 &binding.source,
11470 )
11471 },
11472 |activation_byte| {
11473 Arc::from([ConditionalIncludeProjection {
11474 activation_byte,
11475 required_guards: HashSet::default(),
11476 partial_guards: HashSet::default(),
11477 }])
11478 },
11479 );
11480 projections
11481 .iter()
11482 .cloned()
11483 .filter_map(|projection| {
11484 let required_guards =
11485 merge_preprocessor_guards(&binding.required_guards, &projection.required_guards)?;
11486 let mut projected = binding.clone();
11487 projected.required_guards = required_guards;
11488 project_using_binding_at_activation(projected, projection.activation_byte, root, source)
11489 })
11490 .collect()
11491}
11492
11493fn project_using_binding_at_activation(
11494 mut binding: OrdinaryTypeImport,
11495 activation: usize,
11496 root: Node<'_>,
11497 source: &str,
11498) -> Option<OrdinaryTypeImport> {
11499 let include = include_node_for_activation(root, activation)?;
11500 let include_namespace = enclosing_namespace_components(include, source);
11501 let mut declaration_namespace = include_namespace.clone();
11502 declaration_namespace.extend(binding.declaration_namespace);
11503 binding.declaration_namespace = declaration_namespace;
11504 binding.declaration_byte = activation;
11505 if let Some(prefix) = using_named_scope(include, source) {
11506 let mut projected = prefix;
11507 projected.extend(binding.namespace_scope.take().unwrap_or_default());
11508 binding.scope_depth = projected.len();
11509 binding.block_scope = false;
11510 binding.lexical_depth = projected.len();
11511 binding.namespace_scope = Some(projected);
11512 binding.scope_start = 0;
11513 binding.scope_end = usize::MAX;
11514 Some(binding)
11515 } else if let Some((start, end, depth, block_scope)) = ordinary_using_scope(include) {
11516 binding.namespace_scope = None;
11517 binding.scope_start = start;
11518 binding.scope_end = end;
11519 binding.scope_depth = depth;
11520 binding.block_scope = block_scope;
11521 binding.lexical_depth = include_namespace.len();
11522 Some(binding)
11523 } else {
11524 None
11525 }
11526}
11527
11528pub fn effective_using_bindings_for_name(
11534 visibility: &VisibilityIndex<'_>,
11535 imports: &OrdinaryTypeImportCell,
11536 file: &ProjectFile,
11537 node: Node<'_>,
11538 source: &str,
11539 name: &str,
11540) -> Arc<[OrdinaryTypeImport]> {
11541 imports
11542 .projection_cell(name)
11543 .get_or_init(|| {
11544 let project = project_using_index(visibility);
11545 let name_bindings = project.ordinary_by_name.get(name);
11546 if name_bindings.is_none() && project.directives.is_empty() {
11547 return Arc::from(Vec::new());
11548 }
11549 let root = root_node(node);
11550 let mut projected = Vec::new();
11551 for binding in name_bindings
11552 .into_iter()
11553 .flatten()
11554 .chain(project.directives.iter())
11555 {
11556 if !visibility.source_is_visible(file, &binding.source) {
11557 continue;
11558 }
11559 let target_components = using_binding_target_components_for_name(
11560 binding, project, visibility, file, name,
11561 )
11562 .or_else(|| match &binding.target {
11563 EffectiveUsingTarget::Ordinary {
11564 name: imported_name,
11565 target_components,
11566 ..
11567 } if imported_name == name => Some(target_components.clone()),
11568 EffectiveUsingTarget::Ordinary { .. }
11569 | EffectiveUsingTarget::Namespace { .. } => None,
11570 });
11571 let Some(target_components) = target_components else {
11572 continue;
11573 };
11574 let mut binding = binding.clone();
11575 binding.resolved_target_components = Some(target_components);
11576 projected.extend(project_using_bindings(
11577 binding, visibility, file, root, source,
11578 ));
11579 }
11580 Arc::from(projected)
11581 })
11582 .clone()
11583}
11584
11585pub fn initialized_ordinary_type_imports(
11586 root: Node<'_>,
11587 analyzer: &CppGraphSource<'_>,
11588 visibility: &VisibilityIndex<'_>,
11589 file: &ProjectFile,
11590 source: &str,
11591) -> OrdinaryTypeImportCell {
11592 let cell = visibility.ordinary_type_import_cell(file);
11593 let _ = (root, analyzer, source);
11594 cell
11595}
11596
11597fn effective_using_binding_active(
11602 binding: &OrdinaryTypeImport,
11603 node: Node<'_>,
11604 lexical_scope: &[String],
11605 reference_guards: Option<&HashSet<PreprocessorGuard>>,
11606 visibility: &VisibilityIndex<'_>,
11607 file: &ProjectFile,
11608) -> bool {
11609 effective_using_binding_guards_active(
11610 binding,
11611 node.start_byte(),
11612 reference_guards,
11613 visibility,
11614 file,
11615 ) && binding.namespace_scope.as_ref().map_or_else(
11616 || binding.scope_start <= node.start_byte() && node.end_byte() <= binding.scope_end,
11617 |namespace| lexical_scope.starts_with(namespace),
11618 )
11619}
11620
11621fn effective_using_binding_guards_active(
11622 binding: &OrdinaryTypeImport,
11623 reference_byte: usize,
11624 reference_guards: Option<&HashSet<PreprocessorGuard>>,
11625 visibility: &VisibilityIndex<'_>,
11626 file: &ProjectFile,
11627) -> bool {
11628 binding.declaration_byte <= reference_byte
11629 && reference_guards.is_some_and(|active| binding.required_guards.is_subset(active))
11630 && effective_using_binding_guards_stable_between(binding, reference_byte, visibility, file)
11631}
11632
11633fn effective_using_binding_guards_compatible(
11634 binding: &OrdinaryTypeImport,
11635 reference_byte: usize,
11636 reference_guards: Option<&HashSet<PreprocessorGuard>>,
11637 visibility: &VisibilityIndex<'_>,
11638 file: &ProjectFile,
11639) -> bool {
11640 binding.source != *file
11641 && !binding.required_guards.is_empty()
11642 && binding.declaration_byte <= reference_byte
11643 && reference_guards.is_some_and(|active| {
11644 !binding.required_guards.is_subset(active)
11645 && merge_preprocessor_guards(&binding.required_guards, active).is_some()
11646 })
11647 && effective_using_binding_guards_stable_between(binding, reference_byte, visibility, file)
11648}
11649
11650fn effective_using_binding_guards_stable_between(
11651 binding: &OrdinaryTypeImport,
11652 reference_byte: usize,
11653 visibility: &VisibilityIndex<'_>,
11654 file: &ProjectFile,
11655) -> bool {
11656 visibility.preprocessor_guards_stable_between(
11657 file,
11658 binding.declaration_byte,
11659 reference_byte,
11660 &binding.required_guards,
11661 )
11662}
11663
11664#[allow(clippy::too_many_arguments)]
11665fn binding_type_candidates(
11666 binding: &OrdinaryTypeImport,
11667 active_bindings: &[&OrdinaryTypeImport],
11668 analyzer: &CppGraphSource<'_>,
11669 visibility: &VisibilityIndex<'_>,
11670 file: &ProjectFile,
11671 name: &str,
11672 direct_target: Option<&CodeUnit>,
11673 reference_byte: usize,
11674) -> Vec<(CodeUnit, Vec<String>)> {
11675 ordinary_binding_lookup_targets(binding, active_bindings, name)
11676 .into_iter()
11677 .flat_map(|target| {
11678 let mut candidates = visibility
11679 .visible_identifier_candidates(file, name)
11680 .filter(|candidate| {
11681 (candidate.is_class() || declared_type_alias(analyzer, candidate))
11682 && type_candidate_matches_lookup_components(
11683 analyzer,
11684 visibility,
11685 file,
11686 candidate,
11687 reference_byte,
11688 &target,
11689 )
11690 })
11691 .cloned()
11692 .collect::<Vec<_>>();
11693 if candidates.is_empty()
11694 && matches!(binding.target, EffectiveUsingTarget::Namespace { .. })
11695 && let Some(target_unit) = direct_target
11696 {
11697 let expanded_target_name = macro_expanded_cpp_name_components(
11698 visibility,
11699 file,
11700 target_unit,
11701 reference_byte,
11702 );
11703 if (target_unit.is_class() || declared_type_alias(analyzer, target_unit))
11704 && expanded_target_name == target
11705 && visibility.external_type_candidate_visible_at(
11706 file,
11707 target_unit,
11708 reference_byte,
11709 )
11710 {
11711 candidates.push(target_unit.clone());
11712 }
11713 }
11714 if candidates.is_empty()
11715 && matches!(binding.target, EffectiveUsingTarget::Namespace { .. })
11716 && let Some(target_unit) = direct_target
11717 {
11718 let visible_types = visibility
11719 .visible_identifier_candidates(file, name)
11720 .filter(|candidate| {
11721 candidate.is_class() || declared_type_alias(analyzer, candidate)
11722 })
11723 .collect::<Vec<_>>();
11724 let uniquely_names_target = !visible_types.is_empty()
11725 && visible_types
11726 .iter()
11727 .all(|candidate| same_visible_symbol(candidate, target_unit));
11728 if uniquely_names_target {
11729 candidates.extend(visible_types.into_iter().cloned());
11730 }
11731 }
11732 candidates
11733 .into_iter()
11734 .map(move |candidate| (candidate, target.clone()))
11735 })
11736 .collect()
11737}
11738
11739fn macro_expanded_cpp_name_components(
11740 visibility: &VisibilityIndex<'_>,
11741 file: &ProjectFile,
11742 unit: &CodeUnit,
11743 reference_byte: usize,
11744) -> Vec<String> {
11745 brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
11746 brokk_bifrost_core::analyzer::Language::Cpp,
11747 &cpp_name_for(unit),
11748 )
11749 .into_iter()
11750 .flat_map(|component| {
11751 macro_expanded_cpp_name_component(visibility, file, component, reference_byte)
11752 })
11753 .collect()
11754}
11755
11756fn macro_expanded_cpp_name_component(
11757 visibility: &VisibilityIndex<'_>,
11758 file: &ProjectFile,
11759 component: String,
11760 reference_byte: usize,
11761) -> Vec<String> {
11762 let Some(replacement) =
11763 visibility.object_macro_replacement_at(file, &component, reference_byte)
11764 else {
11765 return vec![component];
11766 };
11767 let expanded = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
11768 brokk_bifrost_core::analyzer::Language::Cpp,
11769 &replacement,
11770 );
11771 if expanded.is_empty() {
11772 vec![component]
11773 } else {
11774 expanded
11775 }
11776}
11777
11778fn type_candidate_matches_lookup_components(
11786 analyzer: &CppGraphSource<'_>,
11787 visibility: &VisibilityIndex<'_>,
11788 file: &ProjectFile,
11789 candidate: &CodeUnit,
11790 reference_byte: usize,
11791 target: &[String],
11792) -> bool {
11793 let expanded = macro_expanded_cpp_name_components(visibility, file, candidate, reference_byte);
11794 if expanded == target {
11795 return true;
11796 }
11797 let Some(cpp) = analyzer.cpp else {
11798 return false;
11799 };
11800 let Some(prepared) = cpp.prepared_syntax(visibility.token(), candidate.source()) else {
11801 return false;
11802 };
11803 let root = prepared.tree().root_node();
11804 for range in analyzer.ranges(candidate) {
11805 let Some(mut current) = root.descendant_for_byte_range(range.start_byte, range.end_byte)
11806 else {
11807 continue;
11808 };
11809 let mut namespaces = Vec::<(Vec<String>, bool)>::new();
11810 loop {
11811 if current.kind() == "namespace_definition"
11812 && let Some(name) = current.child_by_field_name("name")
11813 {
11814 let mut components = Vec::new();
11815 if append_cpp_name_components(name, prepared.source(), &mut components).is_some()
11816 && !components.is_empty()
11817 {
11818 let inline = (0..current.child_count())
11819 .filter_map(|index| current.child(index))
11820 .any(|child| !child.is_named() && child.kind() == "inline");
11821 namespaces.push((components, inline));
11822 }
11823 }
11824 let Some(parent) = current.parent() else {
11825 break;
11826 };
11827 current = parent;
11828 }
11829 namespaces.reverse();
11830 let mut namespace_components = Vec::new();
11831 let mut inline_indexes = HashSet::default();
11832 for (components, inline) in namespaces {
11833 for component in components {
11834 let expanded_component =
11835 macro_expanded_cpp_name_component(visibility, file, component, reference_byte);
11836 if inline {
11837 inline_indexes.extend(
11838 namespace_components.len()
11839 ..namespace_components.len() + expanded_component.len(),
11840 );
11841 }
11842 namespace_components.extend(expanded_component);
11843 }
11844 }
11845 if inline_indexes.is_empty() || !expanded.starts_with(&namespace_components) {
11846 continue;
11847 }
11848 let mut reachable = vec![false; target.len() + 1];
11852 reachable[0] = true;
11853 for (index, component) in expanded.iter().enumerate() {
11854 let mut next = vec![false; target.len() + 1];
11855 for (target_index, reached) in reachable.iter().copied().enumerate() {
11856 if !reached {
11857 continue;
11858 }
11859 if inline_indexes.contains(&index) {
11860 next[target_index] = true;
11861 }
11862 if target
11863 .get(target_index)
11864 .is_some_and(|target_component| target_component == component)
11865 {
11866 next[target_index + 1] = true;
11867 }
11868 }
11869 reachable = next;
11870 }
11871 if reachable[target.len()] {
11872 return true;
11873 }
11874 }
11875 false
11876}
11877
11878#[allow(clippy::too_many_arguments)]
11879fn resolved_type_import(
11880 candidates: Vec<(CodeUnit, Vec<String>)>,
11881 lexical_depth: usize,
11882 is_direct: bool,
11883 analyzer: &CppGraphSource<'_>,
11884 visibility: &VisibilityIndex<'_>,
11885 file: &ProjectFile,
11886 direct_target: Option<&CodeUnit>,
11887) -> OrdinaryTypeImportResolution {
11888 let logical = deduplicate_type_import_candidates(candidates);
11889 let selected = match logical.as_slice() {
11890 [] => return OrdinaryTypeImportResolution::Missing,
11891 [only] => only,
11892 several => {
11897 let units = several
11898 .iter()
11899 .map(|(unit, _)| unit)
11900 .collect::<Vec<&CodeUnit>>();
11901 let Some(spelling) = direct_target.and_then(|target| {
11902 visibility.same_fqn_type_spelling_for_target(analyzer, file, &units, target)
11903 }) else {
11904 return OrdinaryTypeImportResolution::Ambiguous { lexical_depth };
11905 };
11906 several
11907 .iter()
11908 .find(|(unit, _)| same_symbol(unit, spelling))
11909 .expect("the selected spelling is one of the imported candidates")
11910 }
11911 };
11912 OrdinaryTypeImportResolution::Resolved {
11913 target: selected.0.clone(),
11914 target_components: selected.1.clone(),
11915 lexical_depth,
11916 is_direct,
11917 }
11918}
11919
11920#[allow(clippy::too_many_arguments)]
11921fn ordinary_type_import_resolution(
11922 node: Node<'_>,
11923 components: &[String],
11924 global: bool,
11925 analyzer: &CppGraphSource<'_>,
11926 visibility: &VisibilityIndex<'_>,
11927 imports: &OrdinaryTypeImportCell,
11928 file: &ProjectFile,
11929 source: &str,
11930 lexical_scope: &[String],
11931 direct_target: Option<&CodeUnit>,
11932) -> OrdinaryTypeImportResolution {
11933 if global || components.len() != 1 {
11934 return OrdinaryTypeImportResolution::Missing;
11935 }
11936 let name = &components[0];
11937 let bindings = effective_using_bindings_for_name(visibility, imports, file, node, source, name);
11938 if bindings.is_empty() {
11942 return OrdinaryTypeImportResolution::Missing;
11943 }
11944 let reference_guards = preprocessor_guard_environment(node, source);
11945 let active = bindings
11946 .iter()
11947 .filter(|binding| {
11948 effective_using_binding_active(
11949 binding,
11950 node,
11951 lexical_scope,
11952 reference_guards.as_ref(),
11953 visibility,
11954 file,
11955 )
11956 })
11957 .collect::<Vec<_>>();
11958 let transitive = bindings
11959 .iter()
11960 .filter(|binding| {
11961 effective_using_binding_guards_active(
11962 binding,
11963 node.start_byte(),
11964 reference_guards.as_ref(),
11965 visibility,
11966 file,
11967 ) && (binding.namespace_scope.is_some()
11968 || (binding.scope_start <= node.start_byte()
11969 && node.end_byte() <= binding.scope_end))
11970 })
11971 .collect::<Vec<_>>();
11972 ordinary_type_import_resolution_for_bindings(
11973 node,
11974 name,
11975 analyzer,
11976 visibility,
11977 file,
11978 lexical_scope,
11979 direct_target,
11980 &active,
11981 &transitive,
11982 )
11983}
11984
11985#[allow(clippy::too_many_arguments)]
11986fn compatible_foreign_type_import_resolution(
11987 node: Node<'_>,
11988 components: &[String],
11989 global: bool,
11990 analyzer: &CppGraphSource<'_>,
11991 visibility: &VisibilityIndex<'_>,
11992 imports: &OrdinaryTypeImportCell,
11993 file: &ProjectFile,
11994 source: &str,
11995 lexical_scope: &[String],
11996 direct_target: Option<&CodeUnit>,
11997) -> OrdinaryTypeImportResolution {
11998 if global || components.len() != 1 {
11999 return OrdinaryTypeImportResolution::Missing;
12000 }
12001 let name = &components[0];
12002 let bindings = effective_using_bindings_for_name(visibility, imports, file, node, source, name);
12003 if bindings.is_empty() {
12004 return OrdinaryTypeImportResolution::Missing;
12005 }
12006 let reference_guards = preprocessor_guard_environment(node, source);
12007 let compatible = bindings
12008 .iter()
12009 .filter(|binding| {
12010 effective_using_binding_guards_compatible(
12011 binding,
12012 node.start_byte(),
12013 reference_guards.as_ref(),
12014 visibility,
12015 file,
12016 ) && binding.namespace_scope.as_ref().map_or_else(
12017 || binding.scope_start <= node.start_byte() && node.end_byte() <= binding.scope_end,
12018 |namespace| lexical_scope.starts_with(namespace),
12019 )
12020 })
12021 .collect::<Vec<_>>();
12022 let transitive = bindings
12023 .iter()
12024 .filter(|binding| {
12025 effective_using_binding_guards_compatible(
12026 binding,
12027 node.start_byte(),
12028 reference_guards.as_ref(),
12029 visibility,
12030 file,
12031 ) && (binding.namespace_scope.is_some()
12032 || (binding.scope_start <= node.start_byte()
12033 && node.end_byte() <= binding.scope_end))
12034 })
12035 .collect::<Vec<_>>();
12036 ordinary_type_import_resolution_for_bindings(
12037 node,
12038 name,
12039 analyzer,
12040 visibility,
12041 file,
12042 lexical_scope,
12043 direct_target,
12044 &compatible,
12045 &transitive,
12046 )
12047}
12048
12049#[allow(clippy::too_many_arguments)]
12050fn ordinary_type_import_resolution_for_bindings(
12051 node: Node<'_>,
12052 name: &str,
12053 analyzer: &CppGraphSource<'_>,
12054 visibility: &VisibilityIndex<'_>,
12055 file: &ProjectFile,
12056 lexical_scope: &[String],
12057 direct_target: Option<&CodeUnit>,
12058 active: &[&OrdinaryTypeImport],
12059 transitive: &[&OrdinaryTypeImport],
12060) -> OrdinaryTypeImportResolution {
12061 let mut concrete_depths = active
12062 .iter()
12063 .filter(|binding| binding.namespace_scope.is_none())
12064 .map(|binding| binding.scope_depth)
12065 .collect::<Vec<_>>();
12066 concrete_depths.sort_unstable();
12067 concrete_depths.dedup();
12068 for depth in concrete_depths.into_iter().rev() {
12069 let at_tier = active
12070 .iter()
12071 .copied()
12072 .filter(|binding| binding.namespace_scope.is_none() && binding.scope_depth == depth);
12073 let direct = at_tier
12074 .clone()
12075 .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
12076 .flat_map(|binding| {
12077 binding_type_candidates(
12078 binding,
12079 transitive,
12080 analyzer,
12081 visibility,
12082 file,
12083 name,
12084 direct_target,
12085 node.start_byte(),
12086 )
12087 })
12088 .collect::<Vec<_>>();
12089 if !direct.is_empty() {
12090 return resolved_type_import(
12091 direct,
12092 lexical_scope.len(),
12093 true,
12094 analyzer,
12095 visibility,
12096 file,
12097 direct_target,
12098 );
12099 }
12100 let directives = at_tier
12101 .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
12102 .flat_map(|binding| {
12103 binding_type_candidates(
12104 binding,
12105 transitive,
12106 analyzer,
12107 visibility,
12108 file,
12109 name,
12110 direct_target,
12111 node.start_byte(),
12112 )
12113 })
12114 .collect::<Vec<_>>();
12115 if !directives.is_empty() {
12116 return resolved_type_import(
12117 directives,
12118 lexical_scope.len(),
12119 false,
12120 analyzer,
12121 visibility,
12122 file,
12123 direct_target,
12124 );
12125 }
12126 }
12127 for prefix_len in (0..=lexical_scope.len()).rev() {
12128 let tier = &lexical_scope[..prefix_len];
12129 let at_tier = active
12130 .iter()
12131 .copied()
12132 .filter(|binding| binding.namespace_scope.as_deref() == Some(tier));
12133 let direct = at_tier
12134 .clone()
12135 .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Ordinary { .. }))
12136 .flat_map(|binding| {
12137 binding_type_candidates(
12138 binding,
12139 transitive,
12140 analyzer,
12141 visibility,
12142 file,
12143 name,
12144 direct_target,
12145 node.start_byte(),
12146 )
12147 })
12148 .collect::<Vec<_>>();
12149 if !direct.is_empty() {
12150 return resolved_type_import(
12151 direct,
12152 prefix_len,
12153 true,
12154 analyzer,
12155 visibility,
12156 file,
12157 direct_target,
12158 );
12159 }
12160 let directives = at_tier
12161 .filter(|binding| matches!(binding.target, EffectiveUsingTarget::Namespace { .. }))
12162 .flat_map(|binding| {
12163 binding_type_candidates(
12164 binding,
12165 transitive,
12166 analyzer,
12167 visibility,
12168 file,
12169 name,
12170 direct_target,
12171 node.start_byte(),
12172 )
12173 })
12174 .collect::<Vec<_>>();
12175 if !directives.is_empty() {
12176 return resolved_type_import(
12177 directives,
12178 prefix_len,
12179 false,
12180 analyzer,
12181 visibility,
12182 file,
12183 direct_target,
12184 );
12185 }
12186 }
12187 OrdinaryTypeImportResolution::Missing
12188}
12189
12190#[allow(clippy::too_many_arguments)]
12191pub fn resolve_type_components_lexically_at(
12192 node: Node<'_>,
12193 components: &[String],
12194 global: bool,
12195 analyzer: &CppGraphSource<'_>,
12196 visibility: &VisibilityIndex<'_>,
12197 ordinary_type_imports: &OrdinaryTypeImportCell,
12198 file: &ProjectFile,
12199 source: &str,
12200) -> LexicalTypeResolution {
12201 resolve_type_components_lexically_at_inner(
12202 node,
12203 components,
12204 global,
12205 analyzer,
12206 visibility,
12207 ordinary_type_imports,
12208 file,
12209 source,
12210 None,
12211 false,
12212 false,
12213 false,
12214 None,
12215 )
12216}
12217
12218#[allow(clippy::too_many_arguments)]
12226pub fn resolve_type_components_lexically_at_preserving_alias(
12227 node: Node<'_>,
12228 components: &[String],
12229 global: bool,
12230 analyzer: &CppGraphSource<'_>,
12231 visibility: &VisibilityIndex<'_>,
12232 file: &ProjectFile,
12233 source: &str,
12234) -> LexicalTypeResolution {
12235 let ordinary_type_imports =
12236 initialized_ordinary_type_imports(root_node(node), analyzer, visibility, file, source);
12237 resolve_type_components_lexically_at_inner(
12238 node,
12239 components,
12240 global,
12241 analyzer,
12242 visibility,
12243 &ordinary_type_imports,
12244 file,
12245 source,
12246 None,
12247 false,
12248 true,
12249 true,
12250 None,
12251 )
12252}
12253
12254#[allow(clippy::too_many_arguments)]
12255fn resolve_type_components_lexically_at_preserving_alias_with_scope_cache(
12256 node: Node<'_>,
12257 components: &[String],
12258 global: bool,
12259 analyzer: &CppGraphSource<'_>,
12260 visibility: &VisibilityIndex<'_>,
12261 ordinary_type_imports: &OrdinaryTypeImportCell,
12262 file: &ProjectFile,
12263 source: &str,
12264 scope_cache: Option<&LexicalScopeCache>,
12265) -> LexicalTypeResolution {
12266 resolve_type_components_lexically_at_inner(
12267 node,
12268 components,
12269 global,
12270 analyzer,
12271 visibility,
12272 ordinary_type_imports,
12273 file,
12274 source,
12275 None,
12276 false,
12277 true,
12278 false,
12279 scope_cache,
12280 )
12281}
12282
12283#[allow(clippy::too_many_arguments)]
12284fn resolve_type_components_lexically_at_for_target_with_scope_cache(
12285 node: Node<'_>,
12286 components: &[String],
12287 global: bool,
12288 analyzer: &CppGraphSource<'_>,
12289 visibility: &VisibilityIndex<'_>,
12290 ordinary_type_imports: &OrdinaryTypeImportCell,
12291 file: &ProjectFile,
12292 source: &str,
12293 target: &CodeUnit,
12294 apply_structured_prefilter: bool,
12295 scope_cache: Option<&LexicalScopeCache>,
12296) -> LexicalTypeResolution {
12297 resolve_type_components_lexically_at_inner(
12298 node,
12299 components,
12300 global,
12301 analyzer,
12302 visibility,
12303 ordinary_type_imports,
12304 file,
12305 source,
12306 Some(target),
12307 apply_structured_prefilter,
12308 false,
12309 false,
12310 scope_cache,
12311 )
12312}
12313
12314#[allow(clippy::too_many_arguments)]
12315fn resolve_type_components_lexically_at_preserving_alias_with_recovered_scope(
12316 node: Node<'_>,
12317 components: &[String],
12318 global: bool,
12319 analyzer: &CppGraphSource<'_>,
12320 visibility: &VisibilityIndex<'_>,
12321 ordinary_type_imports: &OrdinaryTypeImportCell,
12322 file: &ProjectFile,
12323 source: &str,
12324 recovered_scope: &[String],
12325) -> LexicalTypeResolution {
12326 resolve_type_components_in_authoritative_scope(
12327 node,
12328 components,
12329 global,
12330 analyzer,
12331 visibility,
12332 ordinary_type_imports,
12333 file,
12334 source,
12335 None,
12336 false,
12337 true,
12338 false,
12339 recovered_scope.to_vec(),
12340 )
12341}
12342
12343#[allow(clippy::too_many_arguments)]
12344fn resolve_type_components_lexically_at_for_target_with_recovered_scope(
12345 node: Node<'_>,
12346 components: &[String],
12347 global: bool,
12348 analyzer: &CppGraphSource<'_>,
12349 visibility: &VisibilityIndex<'_>,
12350 ordinary_type_imports: &OrdinaryTypeImportCell,
12351 file: &ProjectFile,
12352 source: &str,
12353 target: &CodeUnit,
12354 apply_structured_prefilter: bool,
12355 recovered_scope: &[String],
12356) -> LexicalTypeResolution {
12357 resolve_type_components_in_authoritative_scope(
12358 node,
12359 components,
12360 global,
12361 analyzer,
12362 visibility,
12363 ordinary_type_imports,
12364 file,
12365 source,
12366 Some(target),
12367 apply_structured_prefilter,
12368 false,
12369 false,
12370 recovered_scope.to_vec(),
12371 )
12372}
12373
12374#[allow(clippy::too_many_arguments)]
12375fn resolve_type_components_lexically_at_inner(
12376 node: Node<'_>,
12377 components: &[String],
12378 global: bool,
12379 analyzer: &CppGraphSource<'_>,
12380 visibility: &VisibilityIndex<'_>,
12381 ordinary_type_imports: &OrdinaryTypeImportCell,
12382 file: &ProjectFile,
12383 source: &str,
12384 direct_target: Option<&CodeUnit>,
12385 apply_structured_prefilter: bool,
12386 preserve_alias: bool,
12387 allow_compatible_foreign_import: bool,
12388 scope_cache: Option<&LexicalScopeCache>,
12389) -> LexicalTypeResolution {
12390 let report_stats = std::env::var_os("BIFROST_CPP_VISIBILITY_STATS").is_some();
12391 let lexical_scope_started = Instant::now();
12392 if report_stats {
12393 eprintln!("BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=started");
12394 }
12395 let lexical_scope = if global {
12396 Vec::new()
12397 } else {
12398 match cached_enclosing_lexical_scope_components_with_unresolved_owner(
12399 node,
12400 analyzer,
12401 visibility,
12402 file,
12403 source,
12404 true,
12405 recovered_macro_decorated_declarator_type(node)
12406 == Some(RecoveredDeclaratorTypeContext::FunctionDefinition),
12407 scope_cache,
12408 ) {
12409 LexicalScopeResolution::Resolved(scope) => scope,
12410 LexicalScopeResolution::Ambiguous => {
12411 if report_stats {
12412 eprintln!(
12413 "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=completed outcome=ambiguous elapsed_ms={}",
12414 lexical_scope_started.elapsed().as_millis(),
12415 );
12416 }
12417 return LexicalTypeResolution::Ambiguous;
12418 }
12419 LexicalScopeResolution::Missing => {
12420 if report_stats {
12421 eprintln!(
12422 "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=completed outcome=missing elapsed_ms={}",
12423 lexical_scope_started.elapsed().as_millis(),
12424 );
12425 }
12426 return LexicalTypeResolution::Missing;
12427 }
12428 }
12429 };
12430 if report_stats {
12431 eprintln!(
12432 "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_scope status=completed components={} elapsed_ms={}",
12433 lexical_scope.len(),
12434 lexical_scope_started.elapsed().as_millis(),
12435 );
12436 }
12437 resolve_type_components_lexically_at_scoped(
12438 node,
12439 components,
12440 global,
12441 analyzer,
12442 visibility,
12443 ordinary_type_imports,
12444 file,
12445 source,
12446 direct_target,
12447 apply_structured_prefilter,
12448 preserve_alias,
12449 allow_compatible_foreign_import,
12450 lexical_scope,
12451 )
12452}
12453
12454#[allow(clippy::too_many_arguments)]
12455fn resolve_type_components_lexically_at_scoped(
12456 node: Node<'_>,
12457 components: &[String],
12458 global: bool,
12459 analyzer: &CppGraphSource<'_>,
12460 visibility: &VisibilityIndex<'_>,
12461 ordinary_type_imports: &OrdinaryTypeImportCell,
12462 file: &ProjectFile,
12463 source: &str,
12464 direct_target: Option<&CodeUnit>,
12465 apply_structured_prefilter: bool,
12466 preserve_alias: bool,
12467 allow_compatible_foreign_import: bool,
12468 mut lexical_scope: Vec<String>,
12469) -> LexicalTypeResolution {
12470 if !global
12471 && components.len() == 1
12472 && let Some(target) = direct_target
12475 && lexical_scope
12476 .last()
12477 .is_none_or(|last| last != &components[0])
12478 && has_malformed_wrapper_function_definition_ancestor(node)
12483 && let Some(indexed_namespace) =
12484 visibility.target_preserving_reference_namespace(analyzer, file, &components[0], target)
12485 && (lexical_scope.is_empty() || !lexical_scope.starts_with(&indexed_namespace))
12486 {
12487 lexical_scope = indexed_namespace;
12488 }
12489 resolve_type_components_in_authoritative_scope(
12490 node,
12491 components,
12492 global,
12493 analyzer,
12494 visibility,
12495 ordinary_type_imports,
12496 file,
12497 source,
12498 direct_target,
12499 apply_structured_prefilter,
12500 preserve_alias,
12501 allow_compatible_foreign_import,
12502 lexical_scope,
12503 )
12504}
12505
12506#[allow(clippy::too_many_arguments)]
12512fn resolve_type_components_in_authoritative_scope(
12513 node: Node<'_>,
12514 components: &[String],
12515 global: bool,
12516 analyzer: &CppGraphSource<'_>,
12517 visibility: &VisibilityIndex<'_>,
12518 ordinary_type_imports: &OrdinaryTypeImportCell,
12519 file: &ProjectFile,
12520 source: &str,
12521 direct_target: Option<&CodeUnit>,
12522 apply_structured_prefilter: bool,
12523 preserve_alias: bool,
12524 allow_compatible_foreign_import: bool,
12525 lexical_scope: Vec<String>,
12526) -> LexicalTypeResolution {
12527 if apply_structured_prefilter
12528 && direct_target.is_some()
12529 && !preserve_alias
12530 && !global
12531 && components.len() == 1
12532 && !visibility.coarse_unqualified_type_reference_may_resolve(file, &components[0])
12533 {
12534 return LexicalTypeResolution::Missing;
12535 }
12536 if !global
12542 && components.len() == 1
12543 && recovered_macro_decorated_type_node(node).is_some()
12544 && let Some(resolution) = recovered_same_file_type_alias_resolution(
12545 node,
12546 components,
12547 analyzer,
12548 visibility,
12549 file,
12550 direct_target,
12551 &lexical_scope,
12552 )
12553 {
12554 return resolution;
12555 }
12556 if apply_structured_prefilter
12557 && let Some(target) = direct_target
12558 && !preserve_alias
12559 && !visibility.structured_type_reference_may_resolve_to_target(
12560 analyzer,
12561 file,
12562 components,
12563 global,
12564 &lexical_scope,
12565 target,
12566 )
12567 {
12568 return LexicalTypeResolution::Missing;
12569 }
12570 let report_stats = std::env::var_os("BIFROST_CPP_VISIBILITY_STATS").is_some();
12571 let lexical_normal_started = Instant::now();
12572 if report_stats {
12573 eprintln!("BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_normal status=started");
12574 }
12575 let normal = if preserve_alias {
12576 visibility.resolve_type_components_lexically_for_forward(
12577 analyzer,
12578 file,
12579 components,
12580 global,
12581 &lexical_scope,
12582 )
12583 } else {
12584 direct_target.map_or_else(
12585 || {
12586 visibility.resolve_type_components_lexically(
12587 analyzer,
12588 file,
12589 components,
12590 global,
12591 &lexical_scope,
12592 )
12593 },
12594 |target| {
12595 visibility.resolve_type_components_lexically_for_target(
12596 analyzer,
12597 file,
12598 components,
12599 global,
12600 &lexical_scope,
12601 target,
12602 )
12603 },
12604 )
12605 };
12606 if report_stats {
12607 eprintln!(
12608 "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=lexical_normal status=completed elapsed_ms={}",
12609 lexical_normal_started.elapsed().as_millis(),
12610 );
12611 }
12612 let normal = match normal {
12613 LexicalTypeResolution::Resolved { ref unit, .. }
12614 if !visibility
12615 .external_type_candidate_visible_in_context(analyzer, file, unit, node)
12616 && !direct_target.is_some_and(|target| {
12617 let candidate_refs = visibility
12618 .visible_identifier_candidates(file, target.identifier())
12619 .collect::<Vec<_>>();
12620 visibility.c_tag_declaration_family_matches_target(
12621 analyzer,
12622 file,
12623 &candidate_refs,
12624 target,
12625 )
12626 }) =>
12627 {
12628 LexicalTypeResolution::Missing
12629 }
12630 resolution => resolution,
12631 };
12632 let normal_depth = match &normal {
12633 LexicalTypeResolution::Resolved { components, .. } => {
12634 Some(components.len().saturating_sub(1))
12635 }
12636 LexicalTypeResolution::Ambiguous | LexicalTypeResolution::Missing => None,
12637 };
12638 let ordinary_import_started = Instant::now();
12644 if report_stats {
12645 eprintln!("BIFROST_CPP_TYPE_LEXICAL_PHASE phase=ordinary_import status=started");
12646 }
12647 let ordinary_import_resolution = ordinary_type_import_resolution(
12648 node,
12649 components,
12650 global,
12651 analyzer,
12652 visibility,
12653 ordinary_type_imports,
12654 file,
12655 source,
12656 &lexical_scope,
12657 direct_target,
12658 );
12659 if report_stats {
12660 eprintln!(
12661 "BIFROST_CPP_TYPE_LEXICAL_PHASE phase=ordinary_import status=completed elapsed_ms={}",
12662 ordinary_import_started.elapsed().as_millis(),
12663 );
12664 }
12665 let resolution = match ordinary_import_resolution {
12666 OrdinaryTypeImportResolution::Missing => normal,
12667 OrdinaryTypeImportResolution::Resolved {
12668 lexical_depth,
12669 is_direct,
12670 ..
12671 } if matches!(&normal, LexicalTypeResolution::Ambiguous)
12672 || normal_depth.is_some_and(|depth| {
12673 depth > lexical_depth || (!is_direct && depth == lexical_depth)
12674 }) =>
12675 {
12676 normal
12677 }
12678 OrdinaryTypeImportResolution::Resolved {
12679 target,
12680 target_components,
12681 ..
12682 } => visibility.resolve_imported_type_candidate(
12683 analyzer,
12684 file,
12685 &target,
12686 &target_components,
12687 direct_target,
12688 preserve_alias,
12689 ),
12690 OrdinaryTypeImportResolution::Ambiguous { lexical_depth }
12691 if normal_depth.is_some_and(|depth| depth > lexical_depth) =>
12692 {
12693 normal
12694 }
12695 OrdinaryTypeImportResolution::Ambiguous { .. } => LexicalTypeResolution::Ambiguous,
12696 };
12697 if !allow_compatible_foreign_import || !matches!(resolution, LexicalTypeResolution::Missing) {
12698 return resolution;
12699 }
12700
12701 match compatible_foreign_type_import_resolution(
12708 node,
12709 components,
12710 global,
12711 analyzer,
12712 visibility,
12713 ordinary_type_imports,
12714 file,
12715 source,
12716 &lexical_scope,
12717 None,
12718 ) {
12719 OrdinaryTypeImportResolution::Missing => resolution,
12720 OrdinaryTypeImportResolution::Resolved {
12721 target,
12722 target_components,
12723 ..
12724 } => visibility.resolve_imported_type_candidate(
12725 analyzer,
12726 file,
12727 &target,
12728 &target_components,
12729 None,
12730 true,
12731 ),
12732 OrdinaryTypeImportResolution::Ambiguous { .. } => LexicalTypeResolution::Ambiguous,
12733 }
12734}
12735
12736fn recovered_same_file_type_alias_resolution(
12737 node: Node<'_>,
12738 components: &[String],
12739 analyzer: &CppGraphSource<'_>,
12740 visibility: &VisibilityIndex<'_>,
12741 file: &ProjectFile,
12742 direct_target: Option<&CodeUnit>,
12743 lexical_scope: &[String],
12744) -> Option<LexicalTypeResolution> {
12745 debug_assert_eq!(components.len(), 1);
12746 debug_assert!(recovered_macro_decorated_type_node(node).is_some());
12747 let alias_provider = analyzer.type_alias_provider()?;
12748 for qualified in lexical_component_tiers(components, false, lexical_scope) {
12749 let candidates = visibility
12750 .visible_identifier_candidates(file, &components[0])
12751 .filter(|candidate| {
12752 candidate.source() == file
12753 && canonical_cpp_scope_components(candidate) == qualified
12754 && visibility
12755 .external_type_candidate_visible_in_context(analyzer, file, candidate, node)
12756 })
12757 .collect::<Vec<_>>();
12758 if candidates.is_empty() {
12759 continue;
12760 }
12761 if candidates
12762 .iter()
12763 .any(|candidate| !alias_provider.is_type_alias(candidate))
12764 {
12765 return None;
12766 }
12767 let unit = if let Some(target) = direct_target {
12768 visibility.unique_type_candidate_preserving_target(
12769 analyzer,
12770 file,
12771 &candidates,
12772 target,
12773 )?
12774 } else {
12775 let first = candidates[0];
12776 if candidates
12777 .iter()
12778 .any(|candidate| !same_visible_symbol(candidate, first))
12779 {
12780 return None;
12781 }
12782 first.clone()
12783 };
12784 return Some(LexicalTypeResolution::Resolved {
12785 unit,
12786 components: qualified,
12787 candidates: candidates.into_iter().cloned().collect(),
12788 });
12789 }
12790 None
12791}
12792
12793fn same_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12794 matches!(
12795 structured_owner_context_resolution(node, ctx),
12796 StructuredOwnerContextResolution::SelfTarget
12797 | StructuredOwnerContextResolution::InheritedTarget
12798 )
12799}
12800
12801fn inherited_target_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12806 let Some(call) = ctx.ancestry.parent(node).filter(|parent| {
12807 parent.kind() == "call_expression" && parent.child_by_field_name("function") == Some(node)
12808 }) else {
12809 return matches!(
12810 structured_owner_context_resolution(node, ctx),
12811 StructuredOwnerContextResolution::InheritedTarget
12812 );
12813 };
12814 let Some(target_owner) = ctx.spec.owner.as_ref() else {
12815 return false;
12816 };
12817 let chain = structured_enclosing_owner_chain(node, ctx);
12818 let Some(innermost) = chain.first() else {
12819 return false;
12820 };
12821 if receiver_owner_matches_target(innermost, target_owner, node.start_byte(), ctx) {
12822 return false;
12823 }
12824 let Some(arity) = ctx
12825 .visibility
12826 .call_arity_evidence(ctx.file, call, ctx.source)
12827 .exact()
12828 else {
12829 return false;
12830 };
12831 for enclosing_owner in &chain {
12832 if receiver_owner_matches_target(enclosing_owner, target_owner, node.start_byte(), ctx) {
12833 return true;
12834 }
12835 match resolve_declaring_callable_owner(
12836 &ctx.analyzer,
12837 ctx.visibility,
12838 ctx.file,
12839 cached_declaring_member_owner(enclosing_owner, ctx),
12840 &ctx.spec.member_name,
12841 arity,
12842 ) {
12843 EnclosingMemberOwnerResolution::Owner(owner) => {
12844 return receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx);
12845 }
12846 EnclosingMemberOwnerResolution::Ambiguous => return false,
12847 EnclosingMemberOwnerResolution::Missing => {}
12850 }
12851 }
12852 false
12853}
12854
12855fn known_non_target_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12856 matches!(
12857 structured_owner_context_resolution(node, ctx),
12858 StructuredOwnerContextResolution::NonTarget
12859 )
12860}
12861
12862fn out_of_line_target_owner_context(node: Node<'_>, ctx: &ScanCtx<'_>) -> bool {
12863 let Some(target_owner) = ctx.spec.owner.as_ref() else {
12864 return false;
12865 };
12866 let mut current = ctx.ancestry.parent(node);
12867 while let Some(parent) = current {
12868 if parent.kind() == "function_definition" {
12869 let Some(owner_lookup) = function_definition_owner_lookup_node(parent) else {
12870 return false;
12871 };
12872 if let Some(owners) = out_of_line_member_definition_owner(
12873 &ctx.analyzer,
12874 ctx.visibility,
12875 ctx.file,
12876 ctx.source,
12877 owner_lookup,
12878 ) && let Some((_, owner)) = owners.innermost()
12879 {
12880 return receiver_owner_matches_target(owner, target_owner, node.start_byte(), ctx);
12881 }
12882 if let Some(owner) = target_guided_out_of_line_owner(owner_lookup, ctx) {
12883 return receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx);
12884 }
12885 return false;
12886 }
12887 current = ctx.ancestry.parent(parent);
12888 }
12889 false
12890}
12891
12892#[derive(Clone, Copy)]
12893enum StructuredOwnerContextResolution {
12894 SelfTarget,
12897 InheritedTarget,
12903 NonTarget,
12904 Ambiguous,
12905 Missing,
12906}
12907
12908fn structured_owner_context_resolution(
12909 node: Node<'_>,
12910 ctx: &ScanCtx<'_>,
12911) -> StructuredOwnerContextResolution {
12912 let Some(target_owner) = ctx.spec.owner.as_ref() else {
12913 return StructuredOwnerContextResolution::Missing;
12914 };
12915 let chain = structured_enclosing_owner_chain(node, ctx);
12916 let Some(innermost) = chain.first() else {
12917 return StructuredOwnerContextResolution::Missing;
12918 };
12919 if receiver_owner_matches_target(innermost, target_owner, node.start_byte(), ctx) {
12920 return StructuredOwnerContextResolution::SelfTarget;
12921 }
12922 for enclosing_owner in &chain {
12927 if receiver_owner_matches_target(enclosing_owner, target_owner, node.start_byte(), ctx) {
12928 return StructuredOwnerContextResolution::InheritedTarget;
12929 }
12930 match cached_declaring_member_owner(enclosing_owner, ctx) {
12931 EnclosingMemberOwnerResolution::Owner(owner)
12932 if receiver_owner_matches_target(&owner, target_owner, node.start_byte(), ctx) =>
12933 {
12934 return StructuredOwnerContextResolution::InheritedTarget;
12935 }
12936 EnclosingMemberOwnerResolution::Owner(_) => {
12937 return StructuredOwnerContextResolution::NonTarget;
12938 }
12939 EnclosingMemberOwnerResolution::Ambiguous => {
12940 return StructuredOwnerContextResolution::Ambiguous;
12941 }
12942 EnclosingMemberOwnerResolution::Missing => {}
12943 }
12944 }
12945 StructuredOwnerContextResolution::Missing
12946}
12947
12948fn cached_declaring_member_owner(
12949 receiver_owner: &CodeUnit,
12950 ctx: &ScanCtx<'_>,
12951) -> EnclosingMemberOwnerResolution {
12952 if let Some(cached) = ctx.member_owner_cache.borrow().get(receiver_owner).cloned() {
12953 return cached;
12954 }
12955 let resolved = resolve_declaring_member_owner(
12956 &ctx.analyzer,
12957 ctx.visibility,
12958 ctx.file,
12959 receiver_owner,
12960 &ctx.spec.member_name,
12961 );
12962 let resolved = if matches!(resolved, EnclosingMemberOwnerResolution::Missing) {
12963 indexed_declaring_owner_for_recovered_member(receiver_owner, ctx)
12964 } else {
12965 resolved
12966 };
12967 ctx.member_owner_cache
12968 .borrow_mut()
12969 .insert(receiver_owner.clone(), resolved.clone());
12970 resolved
12971}
12972
12973fn indexed_declaring_owner_for_recovered_member(
12980 receiver_owner: &CodeUnit,
12981 ctx: &ScanCtx<'_>,
12982) -> EnclosingMemberOwnerResolution {
12983 let Some(spec_owner) = ctx.spec.owner.as_ref() else {
12984 return EnclosingMemberOwnerResolution::Missing;
12985 };
12986 if ctx.spec.kind != TargetKind::Method || ctx.spec.target.source() == spec_owner.source() {
12987 return EnclosingMemberOwnerResolution::Missing;
12988 }
12989 let Some(hierarchy) = ctx.analyzer.type_hierarchy_provider() else {
12990 return EnclosingMemberOwnerResolution::Missing;
12991 };
12992 let Some(receiver_owner) =
12993 ctx.visibility
12994 .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, receiver_owner)
12995 else {
12996 return EnclosingMemberOwnerResolution::Ambiguous;
12997 };
12998 let Some(target_owner) = ctx.spec.owner.as_ref().and_then(|owner| {
12999 ctx.visibility
13000 .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, owner)
13001 }) else {
13002 return EnclosingMemberOwnerResolution::Missing;
13003 };
13004
13005 let owner_declares_member = |owner: &CodeUnit| {
13006 if same_visible_symbol(owner, &target_owner) {
13007 return true;
13008 }
13009 let mut member_fq = owner.fq().clone();
13010 member_fq.push(
13011 ctx.spec
13012 .target
13013 .fq()
13014 .last()
13015 .expect("a method target has a terminal member segment"),
13016 );
13017 ctx.analyzer
13018 .definitions(&member_fq.display(segment_interner()))
13019 .any(|child| child.is_function())
13020 };
13021 if owner_declares_member(&receiver_owner) {
13022 return EnclosingMemberOwnerResolution::Owner(receiver_owner);
13023 }
13024
13025 let mut stack = hierarchy.get_direct_ancestors(&receiver_owner);
13026 let mut propagated_counts: HashMap<CodeUnit, u8> = HashMap::default();
13027 let mut declaring_owner = None;
13028 while let Some(raw_owner) = stack.pop() {
13029 let Some(owner) =
13030 ctx.visibility
13031 .canonical_visible_full_type_unit(&ctx.analyzer, ctx.file, &raw_owner)
13032 else {
13033 return EnclosingMemberOwnerResolution::Ambiguous;
13034 };
13035 let propagated = propagated_counts.entry(owner.clone()).or_default();
13036 if *propagated == 2 {
13037 continue;
13038 }
13039 *propagated += 1;
13040 if owner_declares_member(&owner) {
13041 if declaring_owner.is_some() {
13042 return EnclosingMemberOwnerResolution::Ambiguous;
13043 }
13044 declaring_owner = Some(owner);
13045 continue;
13046 }
13047 stack.extend(hierarchy.get_direct_ancestors(&owner));
13048 }
13049 declaring_owner
13050 .map(EnclosingMemberOwnerResolution::Owner)
13051 .unwrap_or(EnclosingMemberOwnerResolution::Missing)
13052}
13053
13054fn structured_enclosing_owner_chain(node: Node<'_>, ctx: &ScanCtx<'_>) -> Vec<CodeUnit> {
13057 let Some(innermost) = structured_enclosing_owner(node, ctx) else {
13058 return Vec::new();
13059 };
13060 brokk_bifrost_core::analyzer::usages::common::enclosing_class_chain(innermost, |unit| {
13063 ctx.analyzer.parent_of(unit)
13064 })
13065 .collect()
13066}
13067
13068fn structured_enclosing_owner(node: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
13069 if (has_recovered_class_shape_ancestor(node)
13074 || has_malformed_wrapper_function_definition_ancestor(node))
13075 && let Some(owner) = cached_indexed_enclosing_class_owner(node, ctx)
13076 {
13077 return Some(owner);
13078 }
13079 let mut current = ctx.ancestry.parent(node);
13080 while let Some(parent) = current {
13081 if parent.kind() == "function_definition" {
13082 let owner_lookup = function_definition_owner_lookup_node(parent);
13083 if let Some(owner_lookup) = owner_lookup
13084 && let Some(owners) = out_of_line_member_definition_owner(
13085 &ctx.analyzer,
13086 ctx.visibility,
13087 ctx.file,
13088 ctx.source,
13089 owner_lookup,
13090 )
13091 && let Some((_, owner)) = owners.innermost()
13092 {
13093 return Some(owner.clone());
13094 }
13095 if let Some(owner) = cached_indexed_enclosing_class_owner(parent, ctx) {
13096 return Some(owner);
13097 }
13098 if let Some(owner) = enclosing_context(parent, ctx)
13099 .owner
13100 .filter(|owner| owner.is_class())
13101 {
13102 return Some(owner);
13103 }
13104 if let Some(owner_lookup) = owner_lookup
13105 && let Some(owner) = target_guided_out_of_line_owner(owner_lookup, ctx)
13106 {
13107 return Some(owner);
13108 }
13109 break;
13110 }
13111 current = ctx.ancestry.parent(parent);
13112 }
13113 enclosing_context(node, ctx)
13114 .owner
13115 .filter(|owner| owner.is_class())
13116}
13117
13118fn target_guided_out_of_line_owner(function: Node<'_>, ctx: &ScanCtx<'_>) -> Option<CodeUnit> {
13119 let target_owner = ctx.spec.owner.as_ref()?;
13120 let (owner_components, _) = qualified_callable_owner_components(function, ctx.source)?;
13121 let owner_name = owner_components.last()?;
13122 let mut candidates = Vec::new();
13123 for candidate in ctx
13124 .visibility
13125 .visible_identifier_candidates(ctx.file, owner_name)
13126 .filter(|candidate| candidate.is_class())
13127 {
13128 let components = brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path(
13129 brokk_bifrost_core::analyzer::Language::Cpp,
13130 &cpp_name_for(candidate),
13131 );
13132 if !components.ends_with(&owner_components)
13133 || candidates
13134 .iter()
13135 .any(|existing| same_logical_symbol(existing, candidate))
13136 {
13137 continue;
13138 }
13139 candidates.push(candidate.clone());
13140 }
13141 let [candidate] = candidates.as_slice() else {
13142 return None;
13143 };
13144 (same_logical_symbol(candidate, target_owner)
13145 && target_group_contains_owner_peer(candidate, ctx))
13146 .then(|| candidate.clone())
13147}