1use crate::declarations::{cpp_file_using_namespaces, cpp_member_fq, node_text};
19use crate::graph::CppGraphSource;
20use crate::graph::resolver::{
21 VisibilityIndex, cpp_type_name_components, declarator_name_node,
22 qualified_name_has_concrete_scope_separators,
23};
24use crate::graph_support::CppSource;
25use crate::imports::{IncludeTargetIndex, include_paths, resolve_include_targets_with_index};
26use crate::reconcile::{ReconciledIdentity, VisibleClass, reconcile_out_of_line_member_identity};
27use brokk_bifrost_core::analyzer::fq_name::{SegmentKind, segment_interner};
28use brokk_bifrost_core::analyzer::model::{CallableLinkage, Range};
29use brokk_bifrost_core::analyzer::symbol_path::parse_symbol_path_fq;
30use brokk_bifrost_core::analyzer::tree_walk::{node_for_exact_range, subtree_contains};
31use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, Language, ProjectFile};
32use brokk_bifrost_core::hash::HashMap;
33use brokk_bifrost_core::path_utils::rel_path_string;
34use brokk_bifrost_core::profiling;
35use std::collections::BTreeSet;
36use std::sync::Arc;
37use tree_sitter::{Node, Parser, Tree};
38
39#[derive(Debug, Clone, Copy, PartialEq, Eq)]
40pub enum CppCallableUnitRole {
41 DeclarationOnly,
42 Definition,
43 Both,
44 Unknown,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
48pub enum CppOccurrenceRole {
49 DeclarationOnly,
50 Definition,
51 Both,
52 Unknown,
53}
54
55impl CppOccurrenceRole {
56 pub fn api_label(self) -> Option<&'static str> {
57 match self {
58 Self::DeclarationOnly => Some("declaration"),
59 Self::Definition => Some("definition"),
60 Self::Both | Self::Unknown => None,
61 }
62 }
63}
64
65pub struct CppOccurrenceClassifier {
66 tree: Tree,
67}
68
69impl CppOccurrenceClassifier {
70 pub fn new(source: &str) -> Option<Self> {
71 let mut parser = Parser::new();
72 parser
73 .set_language(&tree_sitter_cpp::LANGUAGE.into())
74 .ok()?;
75 parser.parse(source, None).map(|tree| Self { tree })
76 }
77
78 pub fn classify(&self, candidate: &CodeUnit, range: &Range) -> CppOccurrenceRole {
79 cpp_occurrence_role_for_range(self.tree.root_node(), candidate, range)
80 }
81}
82
83pub fn cpp_callable_unit_role(
84 index: &dyn CodeUnitIndex,
85 callable: &CodeUnit,
86) -> CppCallableUnitRole {
87 if !callable.is_callable() {
88 return CppCallableUnitRole::Unknown;
89 }
90 let mut declaration = false;
91 let mut definition = false;
92 for metadata in index.signature_metadata(callable) {
93 if metadata.is_declaration_only() {
94 declaration = true;
95 } else {
96 definition = true;
97 }
98 }
99 match (declaration, definition) {
100 (true, false) => CppCallableUnitRole::DeclarationOnly,
101 (false, true) => CppCallableUnitRole::Definition,
102 (true, true) => CppCallableUnitRole::Both,
103 (false, false) => CppCallableUnitRole::Unknown,
104 }
105}
106
107pub fn cpp_indexed_callable_linkage(
108 index: &dyn CodeUnitIndex,
109 callable: &CodeUnit,
110) -> Option<CallableLinkage> {
111 let mut external = false;
112 for metadata in index.signature_metadata(callable) {
113 match metadata.callable_linkage() {
114 Some(CallableLinkage::Internal) => return Some(CallableLinkage::Internal),
115 Some(CallableLinkage::External) => external = true,
116 None => {}
117 }
118 }
119 external.then_some(CallableLinkage::External)
120}
121
122pub fn cpp_callable_definitions_share_identity_evidence(
128 index: &dyn CodeUnitIndex,
129 left: &CodeUnit,
130 right: &CodeUnit,
131 header_body_related: impl Fn(&ProjectFile, &ProjectFile) -> bool,
132) -> bool {
133 left.source() == right.source()
134 || (left.fq_name() == right.fq_name()
135 && left.signature() == right.signature()
136 && matches!(
137 cpp_indexed_callable_linkage(index, left),
138 Some(CallableLinkage::External)
139 )
140 && matches!(
141 cpp_indexed_callable_linkage(index, right),
142 Some(CallableLinkage::External)
143 )
144 && header_body_related(left.source(), right.source()))
145}
146
147pub fn cpp_callable_definitions_share_identity_evidence_with_visibility(
163 analyzer: &CppGraphSource<'_>,
164 visibility: &VisibilityIndex<'_>,
165 left: &CodeUnit,
166 right: &CodeUnit,
167 header_body_related: impl Fn(&ProjectFile, &ProjectFile) -> bool,
168) -> bool {
169 left.source() == right.source()
170 || (left.fq_name() == right.fq_name()
171 && visibility.same_logical_callable(analyzer, left, right)
172 && matches!(
173 cpp_indexed_callable_linkage(analyzer.index, left),
174 Some(CallableLinkage::External)
175 )
176 && matches!(
177 cpp_indexed_callable_linkage(analyzer.index, right),
178 Some(CallableLinkage::External)
179 )
180 && header_body_related(left.source(), right.source()))
181}
182
183pub fn cpp_is_range_for_binding_name(node: Node<'_>) -> bool {
187 let mut current = Some(node);
188 while let Some(candidate) = current {
189 let Some(parent) = candidate.parent() else {
190 return false;
191 };
192 if parent.kind() == "for_range_loop" {
193 return parent
194 .child_by_field_name("declarator")
195 .is_some_and(|declarator| {
196 cpp_range_for_declarator_contains_name(declarator, node)
197 });
198 }
199 current = Some(parent);
200 }
201 false
202}
203
204pub fn cpp_is_conversion_operator_target_type(mut node: Node<'_>) -> bool {
213 while let Some(parent) = node.parent() {
214 if parent.kind() == "operator_cast" {
215 return true;
216 }
217 if matches!(
218 parent.kind(),
219 "function_declarator" | "declaration" | "function_definition" | "translation_unit"
220 ) {
221 return false;
222 }
223 node = parent;
224 }
225 false
226}
227
228pub fn cpp_is_recovered_macro_character_token_type(node: Node<'_>) -> bool {
238 if node.kind() != "type_identifier" {
239 return false;
240 }
241 let Some(parameter) = node.parent() else {
242 return false;
243 };
244 if parameter.kind() != "parameter_declaration"
245 || parameter.child_by_field_name("type") != Some(node)
246 || parameter.child_by_field_name("declarator").is_some()
247 || parameter
248 .parent()
249 .is_none_or(|parent| parent.kind() != "parameter_list")
250 {
251 return false;
252 }
253
254 parameter
255 .prev_named_sibling()
256 .is_some_and(cpp_is_recovered_character_quote)
257 && parameter
258 .next_named_sibling()
259 .is_some_and(cpp_is_recovered_character_quote)
260}
261
262fn cpp_is_recovered_character_quote(node: Node<'_>) -> bool {
263 node.is_error()
264 && node.child_count() == 1
265 && node
266 .child(0)
267 .is_some_and(|quote| !quote.is_named() && quote.kind() == "'")
268}
269
270pub fn cpp_is_constructor_or_destructor_declarator_name(node: Node<'_>, source: &str) -> bool {
293 cpp_is_declared_constructor_or_destructor_name(node)
294 || cpp_is_recovered_constructor_or_destructor_name(node, source)
295}
296
297fn cpp_is_declared_constructor_or_destructor_name(node: Node<'_>) -> bool {
303 let mut name = node;
304 if let Some(parent) = name.parent()
305 && parent.kind() == "destructor_name"
306 {
307 name = parent;
308 }
309 while let Some(parent) = name.parent() {
313 if parent.kind() != "qualified_identifier"
314 || parent.child_by_field_name("name") != Some(name)
315 {
316 break;
317 }
318 name = parent;
319 }
320 let Some(declarator) = name.parent() else {
321 return false;
322 };
323 if declarator.kind() != "function_declarator"
324 || declarator.child_by_field_name("declarator") != Some(name)
325 {
326 return false;
327 }
328 let Some(owner) = declarator.parent() else {
329 return false;
330 };
331 matches!(owner.kind(), "declaration" | "function_definition")
332 && owner.child_by_field_name("declarator") == Some(declarator)
333 && owner.child_by_field_name("type").is_none()
334}
335
336fn cpp_is_recovered_constructor_or_destructor_name(node: Node<'_>, source: &str) -> bool {
354 if node.kind() != "identifier" {
355 return false;
356 }
357 let Some(call) = node.parent() else {
358 return false;
359 };
360 if call.kind() != "call_expression" || call.child_by_field_name("function") != Some(node) {
361 return false;
362 }
363 let mut current = call.parent();
364 while let Some(ancestor) = current {
365 if ancestor.kind() == "function_definition" {
366 return ancestor
367 .child_by_field_name("declarator")
368 .is_some_and(|declarator| declarator.kind() == "identifier")
369 && cpp_recovered_class_header_names(ancestor, node_text(node, source), source);
370 }
371 current = ancestor.parent();
372 }
373 false
374}
375
376fn cpp_recovered_class_header_names(definition: Node<'_>, name: &str, source: &str) -> bool {
379 let header_end = definition
380 .child_by_field_name("body")
381 .map_or_else(|| definition.end_byte(), |body| body.start_byte());
382 let mut stack = vec![definition];
383 while let Some(node) = stack.pop() {
384 if node.start_byte() >= header_end {
385 continue;
386 }
387 if matches!(
388 node.kind(),
389 "identifier" | "type_identifier" | "namespace_identifier"
390 ) && node_text(node, source) == name
391 {
392 return true;
393 }
394 let mut cursor = node.walk();
395 for child in node.named_children(&mut cursor) {
396 stack.push(child);
397 }
398 }
399 false
400}
401
402fn cpp_range_for_declarator_contains_name(declarator: Node<'_>, target: Node<'_>) -> bool {
403 let mut pending = vec![declarator];
404 while let Some(candidate) = pending.pop() {
405 match candidate.kind() {
406 "identifier" | "field_identifier" => {
407 if cpp_same_node(candidate, target) {
408 return true;
409 }
410 }
411 "structured_binding_declarator" => {
412 let mut cursor = candidate.walk();
413 if candidate
414 .named_children(&mut cursor)
415 .any(|name| cpp_same_node(name, target))
416 {
417 return true;
418 }
419 }
420 "pointer_declarator"
421 | "reference_declarator"
422 | "array_declarator"
423 | "attributed_declarator"
424 | "parenthesized_declarator"
425 | "function_declarator"
426 | "init_declarator" => {
427 if let Some(inner) = cpp_range_for_inner_declarator(candidate) {
428 pending.push(inner);
429 }
430 }
431 _ => {}
432 }
433 }
434 false
435}
436
437fn cpp_range_for_inner_declarator(node: Node<'_>) -> Option<Node<'_>> {
438 node.child_by_field_name("declarator").or_else(|| {
439 let mut cursor = node.walk();
440 node.named_children(&mut cursor).find(|child| {
441 matches!(
442 child.kind(),
443 "identifier"
444 | "field_identifier"
445 | "structured_binding_declarator"
446 | "pointer_declarator"
447 | "reference_declarator"
448 | "array_declarator"
449 | "attributed_declarator"
450 | "parenthesized_declarator"
451 | "function_declarator"
452 | "init_declarator"
453 )
454 })
455 })
456}
457
458fn cpp_same_node(left: Node<'_>, right: Node<'_>) -> bool {
459 left.id() == right.id()
460 && left.start_byte() == right.start_byte()
461 && left.end_byte() == right.end_byte()
462}
463
464pub fn cpp_header_body_files_are_related(
471 left: &ProjectFile,
472 right: &ProjectFile,
473 implementation_imports: &[String],
474 include_targets: &IncludeTargetIndex,
475) -> bool {
476 let (header, implementation) = if cpp_source_path_is_header(left) {
477 (left, right)
478 } else if cpp_source_path_is_header(right) {
479 (right, left)
480 } else {
481 return false;
482 };
483 if cpp_source_path_is_header(implementation) {
484 return false;
485 }
486 implementation_imports
487 .iter()
488 .flat_map(|import| include_paths(std::slice::from_ref(import)))
489 .any(|include| {
490 let targets =
491 resolve_include_targets_with_index(implementation, &include, include_targets);
492 targets.len() == 1 && targets.first() == Some(header)
493 })
494}
495
496pub fn cpp_header_body_implementation_file<'a>(
500 left: &'a ProjectFile,
501 right: &'a ProjectFile,
502) -> Option<&'a ProjectFile> {
503 let implementation = if cpp_source_path_is_header(left) {
504 right
505 } else if cpp_source_path_is_header(right) {
506 left
507 } else {
508 return None;
509 };
510 (!cpp_source_path_is_header(implementation)).then_some(implementation)
511}
512
513pub fn cpp_source_path_is_header(source: &ProjectFile) -> bool {
514 let path = rel_path_string(source).to_ascii_lowercase();
515 matches!(
516 path.rsplit('.').next(),
517 Some("h" | "hin" | "hh" | "hpp" | "hxx")
518 )
519}
520
521pub fn cpp_occurrence_role_for_range(
522 root: Node<'_>,
523 candidate: &CodeUnit,
524 range: &Range,
525) -> CppOccurrenceRole {
526 if !candidate.is_callable() && !candidate.is_class() {
527 return CppOccurrenceRole::Both;
528 }
529 let Some(node) = cpp_declaration_node_for_range(root, range) else {
530 return CppOccurrenceRole::Unknown;
531 };
532 if candidate.is_callable() {
533 return if subtree_contains(node, |descendant| {
534 descendant.kind() == "function_definition"
535 && descendant.child_by_field_name("body").is_some()
536 }) {
537 CppOccurrenceRole::Definition
538 } else {
539 CppOccurrenceRole::DeclarationOnly
540 };
541 }
542 if node.kind() == "function_definition" && node.child_by_field_name("body").is_some() {
543 return CppOccurrenceRole::Definition;
544 }
545 if !subtree_contains(node, |descendant| {
546 matches!(
547 descendant.kind(),
548 "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
549 )
550 }) {
551 return CppOccurrenceRole::Both;
552 }
553 if subtree_contains(node, |descendant| {
554 matches!(
555 descendant.kind(),
556 "class_specifier" | "struct_specifier" | "union_specifier" | "enum_specifier"
557 ) && descendant.child_by_field_name("body").is_some()
558 }) {
559 CppOccurrenceRole::Definition
560 } else {
561 CppOccurrenceRole::DeclarationOnly
562 }
563}
564
565fn cpp_declaration_node_for_range<'tree>(root: Node<'tree>, range: &Range) -> Option<Node<'tree>> {
566 node_for_exact_range(root, range).or_else(|| {
567 root.descendant_for_byte_range(range.start_byte, range.end_byte)
568 .and_then(|mut node| {
569 while node.start_byte() > range.start_byte || node.end_byte() < range.end_byte {
570 node = node.parent()?;
571 }
572 Some(node)
573 })
574 })
575}
576
577#[derive(Default)]
589pub struct CppReconciledDefinitionIndex {
590 pub rekeyed: Vec<CodeUnit>,
592 pub provisional_of: HashMap<CodeUnit, CodeUnit>,
594}
595
596#[derive(Debug, Clone, PartialEq, Eq, Hash)]
612pub struct CppReconcileGroupKey {
613 pub member_identifier: String,
616 pub owner_terminal: Option<String>,
620}
621
622pub fn cpp_reconcile_group_key(fq_name: &str) -> Option<CppReconcileGroupKey> {
629 let interner = segment_interner();
630 let query_fq = parse_symbol_path_fq(Language::Cpp, fq_name, interner);
631 let (member_identifier, _) = interner.resolve(query_fq.last()?);
632 if member_identifier.is_empty() {
633 return None;
634 }
635 let owner_terminal = query_fq.segments().len().checked_sub(2).map(|penultimate| {
645 let (text, _) = interner.resolve(query_fq.segments()[penultimate]);
646 text.rsplit_once('$')
651 .map_or(text, |(_, tail)| tail)
652 .to_string()
653 });
654 Some(CppReconcileGroupKey {
655 member_identifier: member_identifier.to_string(),
656 owner_terminal,
657 })
658}
659
660pub struct CppReconcileCandidates {
666 by_owner_terminal: HashMap<String, Vec<CodeUnit>>,
667 all: Vec<CodeUnit>,
671}
672
673impl CppReconcileCandidates {
674 fn for_group(&self, key: &CppReconcileGroupKey) -> &[CodeUnit] {
677 match &key.owner_terminal {
678 Some(owner_terminal) => self
679 .by_owner_terminal
680 .get(owner_terminal)
681 .map_or(&[][..], Vec::as_slice),
682 None => &self.all,
683 }
684 }
685
686 pub fn iter(&self) -> impl Iterator<Item = &CodeUnit> {
688 self.all.iter()
689 }
690
691 pub fn bucketed_len(&self) -> usize {
694 self.by_owner_terminal.values().map(Vec::len).sum()
695 }
696}
697
698pub fn cpp_reconcile_candidates(
706 cpp: &dyn CppSource,
707 member_identifier: &str,
708 keep_going: &dyn Fn() -> bool,
709) -> Option<CppReconcileCandidates> {
710 let candidates: BTreeSet<CodeUnit> = {
711 let _lookup =
712 profiling::scope_with(|| format!("cpp.reconcile.lookup[{member_identifier}]"));
713 cpp.lookup_candidates_by_identifier(member_identifier)
714 };
715 profiling::note_with(|| {
716 format!(
717 "cpp.reconcile.candidates[{member_identifier}] n={}",
718 candidates.len()
719 )
720 });
721
722 let interner = segment_interner();
723 let mut by_owner_terminal: HashMap<String, Vec<CodeUnit>> = HashMap::default();
724 let mut all = Vec::new();
725 for (index, unit) in candidates.into_iter().enumerate() {
726 if index % CANDIDATE_BUCKETING_POLL_STRIDE == 0 && !keep_going() {
730 return None;
731 }
732 if !unit.is_callable() {
733 continue;
734 }
735 let owner_terminal = unit
736 .fq()
737 .segments()
738 .iter()
739 .filter_map(|&segment| {
740 let (text, kind) = interner.resolve(segment);
741 matches!(
745 kind,
746 SegmentKind::Package | SegmentKind::Type | SegmentKind::Nested
747 )
748 .then_some(text)
749 })
750 .last();
751 if let Some(owner_terminal) = owner_terminal {
752 by_owner_terminal
753 .entry(owner_terminal.to_string())
754 .or_default()
755 .push(unit.clone());
756 }
757 all.push(unit);
758 }
759 Some(CppReconcileCandidates {
760 by_owner_terminal,
761 all,
762 })
763}
764
765const CANDIDATE_BUCKETING_POLL_STRIDE: usize = 256;
767
768pub fn cpp_reconcile_group(
785 cpp: &dyn CppSource,
786 key: &CppReconcileGroupKey,
787 candidates: &CppReconcileCandidates,
788 keep_going: &dyn Fn() -> bool,
789 on_candidate: &dyn Fn(),
790) -> Option<HashMap<String, Arc<CppReconciledDefinitionIndex>>> {
791 let _scope = profiling::scope_with(|| {
792 format!(
793 "cpp.reconciled.build[{}#{}]",
794 key.member_identifier,
795 key.owner_terminal.as_deref().unwrap_or("*")
796 )
797 });
798 let mut groups: HashMap<String, CppReconciledDefinitionIndex> = HashMap::default();
799 let mut using_by_file: HashMap<ProjectFile, Arc<Vec<String>>> = HashMap::default();
800 for unit in candidates.for_group(key) {
801 if !keep_going() {
806 return None;
807 }
808 on_candidate();
809 let _candidate =
812 profiling::scope_with(|| format!("cpp.reconcile.candidate[{}]", unit.fq_name()));
813 let role = {
814 let _role = profiling::scope("cpp.reconcile.role");
815 cpp_callable_unit_role(cpp, unit)
816 };
817 if !matches!(
818 role,
819 CppCallableUnitRole::Definition | CppCallableUnitRole::Both
820 ) {
821 continue;
822 }
823 let Some(reconciled) = cpp_reconcile_definition_identity(cpp, unit, &mut using_by_file)
824 else {
825 continue;
826 };
827 let canonical_fq = reconciled.fq_name();
828 if unit.fq_name() == canonical_fq {
835 continue;
836 }
837 let short_name = format!("{}.{}", reconciled.owner_chain, reconciled.member);
846 let fq = cpp_member_fq(&reconciled.package, &short_name);
847 let rekeyed = CodeUnit::with_signature_and_fq(
848 unit.source().clone(),
849 unit.kind(),
850 reconciled.package,
851 short_name,
852 unit.signature().map(str::to_string),
853 unit.is_synthetic(),
854 fq,
855 );
856 let index = groups.entry(canonical_fq).or_default();
857 index.rekeyed.push(rekeyed.clone());
858 index.provisional_of.insert(rekeyed, unit.clone());
859 }
860 Some(
861 groups
862 .into_iter()
863 .map(|(canonical_fq, index)| (canonical_fq, Arc::new(index)))
864 .collect(),
865 )
866}
867
868fn cpp_reconcile_definition_identity(
874 cpp: &dyn CppSource,
875 unit: &CodeUnit,
876 using_by_file: &mut HashMap<ProjectFile, Arc<Vec<String>>>,
877) -> Option<ReconciledIdentity> {
878 let interner = segment_interner();
888 let mut provisional_owner_segments: Vec<&str> = Vec::new();
889 let mut member: Option<&str> = None;
890 for &segment in unit.fq().segments() {
891 let (text, kind) = interner.resolve(segment);
892 match kind {
893 SegmentKind::Package | SegmentKind::Type | SegmentKind::Nested => {
894 if member.is_some() {
898 return None;
899 }
900 if !text.is_empty() {
901 provisional_owner_segments.push(text);
902 }
903 }
904 SegmentKind::Member => member = Some(text),
905 _ => return None,
906 }
907 }
908 let member = member?;
909 let structured_owner_segments =
914 cpp_structured_out_of_line_owner_segments(cpp, unit).filter(|segments| segments.len() == 1);
915 let owner_segments = structured_owner_segments.as_ref().map_or_else(
916 || provisional_owner_segments,
917 |segments| segments.iter().map(String::as_str).collect(),
918 );
919 if owner_segments.is_empty() {
920 return None;
921 }
922
923 let using = using_by_file
924 .entry(unit.source().clone())
925 .or_insert_with(|| {
926 Arc::new(
927 cpp.file_source(unit.source())
928 .map(|source| cpp_file_using_namespaces(&source))
929 .unwrap_or_default(),
930 )
931 })
932 .clone();
933 let mut namespace_candidates: Vec<&str> = vec![""];
934 namespace_candidates.extend(using.iter().map(String::as_str));
935
936 let visible = {
937 let _visible = profiling::scope_with(|| {
938 format!("cpp.reconcile.visible[{}]", rel_path_string(unit.source()))
939 });
940 cpp.visible_type_units(unit.source())
941 };
942 let class_table: Vec<VisibleClass> = visible
943 .iter()
944 .filter(|candidate| candidate.is_class())
945 .map(|candidate| VisibleClass {
946 package: candidate.package_name(),
947 nested_short_name: candidate.short_name(),
948 })
949 .collect();
950
951 reconcile_out_of_line_member_identity(
952 &owner_segments,
953 member,
954 &namespace_candidates,
955 &class_table,
956 )
957}
958
959fn cpp_structured_out_of_line_owner_segments(
966 cpp: &dyn CppSource,
967 unit: &CodeUnit,
968) -> Option<Vec<String>> {
969 let prepared = cpp.prepared_syntax(unit.source())?;
970 let root = prepared.tree().root_node();
971 for range in cpp.ranges(unit) {
972 let mut current = cpp_declaration_node_for_range(root, &range)?;
973 let function = loop {
974 if current.kind() == "function_definition" {
975 break current;
976 }
977 current = current.parent()?;
978 };
979 if function.child_by_field_name("body").is_none() {
980 continue;
981 }
982 let declarator = function.child_by_field_name("declarator")?;
983 let name = declarator_name_node(declarator)?;
984 if !qualified_name_has_concrete_scope_separators(name) {
985 continue;
986 }
987 let mut components = cpp_type_name_components(name, prepared.source())?;
988 components.pop()?;
989 if !components.is_empty() {
990 return Some(components);
991 }
992 }
993 None
994}
995
996#[cfg(test)]
997mod tests {
998 use super::*;
999
1000 fn parse_cpp(source: &str) -> Tree {
1001 let mut parser = Parser::new();
1002 parser
1003 .set_language(&tree_sitter_cpp::LANGUAGE.into())
1004 .expect("cpp language");
1005 parser.parse(source, None).expect("cpp tree")
1006 }
1007
1008 fn is_declarator_name(tree: &Tree, source: &str, start: usize, text: &str) -> bool {
1009 let end = start + text.len();
1010 assert_eq!(&source[start..end], text, "the probe must name the token");
1011 let node = tree
1012 .root_node()
1013 .named_descendant_for_byte_range(start, end)
1014 .expect("a node spans the probed range");
1015 assert_eq!(
1016 (node.start_byte(), node.end_byte()),
1017 (start, end),
1018 "the probed range must be exactly one node: {}",
1019 node.to_sexp()
1020 );
1021 cpp_is_constructor_or_destructor_declarator_name(node, source)
1022 }
1023
1024 fn is_conversion_target(tree: &Tree, source: &str, start: usize, text: &str) -> bool {
1025 let end = start + text.len();
1026 assert_eq!(&source[start..end], text, "the probe must name the token");
1027 let node = tree
1028 .root_node()
1029 .named_descendant_for_byte_range(start, end)
1030 .expect("a node spans the probed range");
1031 assert_eq!(
1032 (node.start_byte(), node.end_byte()),
1033 (start, end),
1034 "the probed range must be exactly one node: {}",
1035 node.to_sexp()
1036 );
1037 cpp_is_conversion_operator_target_type(node)
1038 }
1039
1040 fn is_recovered_macro_character_type(
1041 tree: &Tree,
1042 source: &str,
1043 start: usize,
1044 text: &str,
1045 ) -> bool {
1046 let end = start + text.len();
1047 assert_eq!(&source[start..end], text, "the probe must name the token");
1048 let node = tree
1049 .root_node()
1050 .named_descendant_for_byte_range(start, end)
1051 .expect("a node spans the probed range");
1052 cpp_is_recovered_macro_character_token_type(node)
1053 }
1054
1055 #[test]
1056 fn recovered_macro_character_tokens_are_not_type_references() {
1057 let source = concat!(
1058 "struct I {};\n",
1059 "#define STRING_TOKEN_(name, ...)\n",
1060 "struct Schema {\n",
1061 " STRING_TOKEN_(MaxItems, 'm', 'I')\n",
1062 " void ordinary(I value);\n",
1063 " void malformed(I value, @);\n",
1064 " void use() { I value; consume('I'); }\n",
1065 "};\n",
1066 );
1067 let tree = parse_cpp(source);
1068 let recovered_m = source.find("'m'").expect("recovered m") + 1;
1069 let recovered_i = source.find("'I'").expect("recovered I") + 1;
1070 for (label, start, text) in [
1071 ("lowercase character token", recovered_m, "m"),
1072 ("uppercase character token", recovered_i, "I"),
1073 ] {
1074 assert!(
1075 is_recovered_macro_character_type(&tree, source, start, text),
1076 "{label} must match the exact recovery role"
1077 );
1078 }
1079
1080 let macro_first_argument = source.find("MaxItems").expect("macro first argument");
1081 let ordinary = source.find("ordinary(I").expect("ordinary parameter") + "ordinary(".len();
1082 let malformed =
1083 source.find("malformed(I").expect("malformed parameter") + "malformed(".len();
1084 let local = source
1085 .find("I value; consume")
1086 .expect("local type reference");
1087 let expression_character = source.rfind("'I'").expect("expression character") + 1;
1088 for (label, start, text) in [
1089 ("unquoted macro argument", macro_first_argument, "MaxItems"),
1090 ("ordinary parameter type", ordinary, "I"),
1091 ("parameter beside another error", malformed, "I"),
1092 ("local type reference", local, "I"),
1093 ("expression character literal", expression_character, "I"),
1094 ] {
1095 assert!(
1096 !is_recovered_macro_character_type(&tree, source, start, text),
1097 "{label} must remain outside the recovery role"
1098 );
1099 }
1100 }
1101
1102 #[test]
1103 fn conversion_operator_target_components_are_identity_syntax_only() {
1104 let source = concat!(
1105 "namespace other { struct Target {}; template<class T> struct Box {}; }\n",
1106 "using other::Target;\n",
1107 "struct Source {\n",
1108 " operator Target() const;\n",
1109 " operator other::Target() const { return other::Target{}; }\n",
1110 " template<class T> operator other::Box<T>() const { return {}; }\n",
1111 " operator other::Target const&() const;\n",
1112 " operator other::Target*() const;\n",
1113 " other::Target ordinary() const {\n",
1114 " return reinterpret_cast<other::Target&>(*this);\n",
1115 " }\n",
1116 " other::Target operator+() const { return {}; }\n",
1117 "};\n",
1118 );
1119 let tree = parse_cpp(source);
1120
1121 let bare = source.find("operator Target").expect("bare target") + "operator ".len();
1122 let qualified = source
1123 .find("operator other::Target()")
1124 .expect("qualified target")
1125 + "operator ".len();
1126 let template = source
1127 .find("operator other::Box<T>")
1128 .expect("template target")
1129 + "operator ".len();
1130 let cv_reference = source
1131 .find("operator other::Target const&")
1132 .expect("cv-reference target")
1133 + "operator other::".len();
1134 let pointer = source
1135 .find("operator other::Target*")
1136 .expect("pointer target")
1137 + "operator other::".len();
1138
1139 for (label, start, text) in [
1140 ("bare target", bare, "Target"),
1141 ("qualified target scope", qualified, "other"),
1142 (
1143 "qualified target name",
1144 qualified + "other::".len(),
1145 "Target",
1146 ),
1147 ("template target scope", template, "other"),
1148 ("template target name", template + "other::".len(), "Box"),
1149 (
1150 "template target argument",
1151 template + "other::Box<".len(),
1152 "T",
1153 ),
1154 ("cv-reference target", cv_reference, "Target"),
1155 ("pointer target", pointer, "Target"),
1156 ] {
1157 assert!(
1158 is_conversion_target(&tree, source, start, text),
1159 "the {label} at byte {start} belongs to the conversion identity"
1160 );
1161 }
1162
1163 let ordinary_return = source
1164 .find("other::Target ordinary")
1165 .expect("ordinary return");
1166 let body_cast = source
1167 .find("reinterpret_cast<other::Target")
1168 .expect("body cast")
1169 + "reinterpret_cast<".len();
1170 let overloaded_return = source
1171 .find("other::Target operator+")
1172 .expect("overloaded operator return");
1173 for (label, start) in [
1174 ("ordinary return type", ordinary_return),
1175 ("body cast target", body_cast),
1176 ("overloaded-operator return type", overloaded_return),
1177 ] {
1178 assert!(
1179 !is_conversion_target(&tree, source, start, "other"),
1180 "the {label} at byte {start} stays a reference"
1181 );
1182 }
1183 }
1184
1185 #[test]
1190 fn declared_constructor_and_destructor_declarator_names_are_not_references() {
1191 let source = concat!(
1192 "class Foo {\n",
1193 "public:\n",
1194 " Foo();\n",
1195 " Foo(const Foo&);\n",
1196 " ~Foo();\n",
1197 " void m();\n",
1198 "};\n",
1199 "Foo::Foo() {}\n",
1200 "Foo::~Foo() {}\n",
1201 "void Foo::m() {}\n",
1202 );
1203 let tree = parse_cpp(source);
1204
1205 for (label, start, text) in [
1206 (
1207 "constructor declaration",
1208 source.find("Foo();").expect("ctor"),
1209 "Foo",
1210 ),
1211 (
1212 "copy constructor declaration",
1213 source.find("Foo(const Foo&);").expect("copy ctor"),
1214 "Foo",
1215 ),
1216 (
1217 "destructor name",
1218 source.find("~Foo();").expect("dtor"),
1219 "~Foo",
1220 ),
1221 (
1222 "identifier inside the destructor name",
1223 source.find("~Foo();").expect("dtor") + "~".len(),
1224 "Foo",
1225 ),
1226 (
1227 "out-of-line constructor definition name",
1228 source.find("Foo::Foo() {}").expect("out-of-line ctor") + "Foo::".len(),
1229 "Foo",
1230 ),
1231 (
1232 "out-of-line destructor definition name",
1233 source.find("Foo::~Foo() {}").expect("out-of-line dtor") + "Foo::".len(),
1234 "~Foo",
1235 ),
1236 ] {
1237 assert!(
1238 is_declarator_name(&tree, source, start, text),
1239 "the {label} at byte {start} is a declaration occurrence"
1240 );
1241 }
1242
1243 for (label, start, text) in [
1244 (
1245 "class name",
1246 source.find("class Foo {").expect("class") + "class ".len(),
1247 "Foo",
1248 ),
1249 (
1250 "parameter type",
1251 source.find("const Foo&").expect("parameter type") + "const ".len(),
1252 "Foo",
1253 ),
1254 (
1255 "owning scope of an out-of-line constructor",
1256 source.find("Foo::Foo() {}").expect("out-of-line ctor"),
1257 "Foo",
1258 ),
1259 (
1260 "owning scope of an out-of-line destructor",
1261 source.find("Foo::~Foo() {}").expect("out-of-line dtor"),
1262 "Foo",
1263 ),
1264 (
1265 "out-of-line method name",
1266 source.find("void Foo::m() {}").expect("out-of-line method") + "void Foo::".len(),
1267 "m",
1268 ),
1269 ] {
1270 assert!(
1271 !is_declarator_name(&tree, source, start, text),
1272 "the {label} at byte {start} stays a reference"
1273 );
1274 }
1275 }
1276
1277 #[test]
1281 fn constructor_call_sites_stay_references() {
1282 let source = concat!(
1283 "struct B { B(int); };\n",
1284 "struct D : B {\n",
1285 " D(int x) : B(x), base_(x) {}\n",
1286 " int base_;\n",
1287 "};\n",
1288 "void g() {\n",
1289 " D* p = new D(1);\n",
1290 " D x(2);\n",
1291 " D(3);\n",
1292 " g();\n",
1293 "}\n",
1294 );
1295 let tree = parse_cpp(source);
1296
1297 let inline_declarator = source.find("D(int x)").expect("inline constructor");
1298 assert!(
1299 is_declarator_name(&tree, source, inline_declarator, "D"),
1300 "an inline constructor definition name is still a declarator"
1301 );
1302
1303 for (label, start, text) in [
1304 (
1305 "base member initializer",
1306 source.find(": B(x)").expect("base initializer") + ": ".len(),
1307 "B",
1308 ),
1309 (
1310 "field member initializer",
1311 source.find("base_(x) {}").expect("field initializer"),
1312 "base_",
1313 ),
1314 (
1315 "new expression type",
1316 source.find("new D(1)").expect("new expression") + "new ".len(),
1317 "D",
1318 ),
1319 (
1320 "direct initialization type",
1321 source.find("D x(2)").expect("direct initialization"),
1322 "D",
1323 ),
1324 (
1325 "temporary construction statement",
1326 source.find("D(3)").expect("temporary"),
1327 "D",
1328 ),
1329 (
1330 "recursive call in a real body",
1331 source.find("g();").expect("recursive call"),
1332 "g",
1333 ),
1334 ] {
1335 assert!(
1336 !is_declarator_name(&tree, source, start, text),
1337 "the {label} at byte {start} is a reference"
1338 );
1339 }
1340 }
1341
1342 #[test]
1347 fn a_constructor_declarator_the_parse_read_as_a_call_is_not_a_reference() {
1348 let source = concat!(
1349 "class SAMPLE_EXPORT Properties {\n",
1350 " public:\n",
1351 " Properties();\n",
1352 " DISALLOW_COPY_AND_ASSIGN(Properties);\n",
1353 " int size() const;\n",
1354 " int total() { return size(); }\n",
1355 "};\n",
1356 );
1357 let tree = parse_cpp(source);
1358
1359 let recovered = source.find("Properties();").expect("recovered constructor");
1360 assert!(
1361 is_declarator_name(&tree, source, recovered, "Properties"),
1362 "a constructor declaration the parse read as a call is still a declarator"
1363 );
1364
1365 for (label, start, text) in [
1366 (
1367 "class name in the recovered header",
1368 source
1369 .find("class SAMPLE_EXPORT Properties")
1370 .expect("class")
1371 + "class SAMPLE_EXPORT ".len(),
1372 "Properties",
1373 ),
1374 (
1375 "macro invocation in the recovered body",
1376 source
1377 .find("DISALLOW_COPY_AND_ASSIGN(Properties);")
1378 .expect("macro invocation"),
1379 "DISALLOW_COPY_AND_ASSIGN",
1380 ),
1381 (
1382 "call inside a method body the recovery kept",
1383 source.find("return size();").expect("member call") + "return ".len(),
1384 "size",
1385 ),
1386 ] {
1387 assert!(
1388 !is_declarator_name(&tree, source, start, text),
1389 "the {label} at byte {start} stays a reference"
1390 );
1391 }
1392 }
1393}