1use crate::analyzer::code_unit_index::CodeUnitIndex;
2use crate::analyzer::model::{CodeUnit, ImportInfo, ProjectFile};
3use crate::analyzer::pool_memo::PoolSafeMemo;
4use crate::analyzer::query_token::QueryToken;
5use crate::cancellation::CancellationToken;
6use crate::compact_graph::{CompactRows, CompactRowsBuilder, normalize_indexed_edges};
7use crate::hash::{HashMap, HashSet};
8use std::any::Any;
9use std::collections::{BTreeSet, VecDeque};
10use std::sync::Arc;
11
12use rayon::prelude::*;
13
14use serde_json::Value;
15
16pub trait CapabilityProvider: Any {
17 fn as_any(&self) -> &dyn Any;
18}
19
20#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct FileDependencyFacts {
29 pub imports: Vec<ImportInfo>,
30 pub contains_tests: Option<bool>,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct AdditionalFileDependencies {
41 pub membership_cause: Option<CSharpCompilationMembershipOpenCause>,
43 pub dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>,
44 pub complete: bool,
45}
46
47#[derive(Debug, Clone, Copy, PartialEq, Eq)]
50pub enum CSharpCompilationMembershipCompleteness {
51 Complete,
52 Open(CSharpCompilationMembershipOpenCause),
53}
54
55impl CSharpCompilationMembershipCompleteness {
56 pub fn cause(self) -> Option<CSharpCompilationMembershipOpenCause> {
57 match self {
58 Self::Complete => None,
59 Self::Open(cause) => Some(cause),
60 }
61 }
62}
63
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub enum CSharpCompilationMembershipOpenCause {
66 DirectoryOmitted,
67 ProjectFileUnknown(crate::analyzer::project::WorkspaceFileOmissionReason),
71 ListingUnavailable,
72}
73
74#[derive(Debug, Clone, PartialEq, Eq, Hash)]
79pub struct ImportLookupDependency {
80 pub import_ordinal: u32,
81 pub consulted_file: ProjectFile,
82 pub name: String,
83}
84
85#[derive(Debug, Clone, Default, PartialEq, Eq)]
89pub struct ImportResolutionDependencies {
90 pub lookups: Vec<ImportLookupDependency>,
91 pub missing_module_path_keys: Vec<(u32, String)>,
92}
93
94#[derive(Debug, Clone, PartialEq, Eq, Hash)]
100pub struct ImportGraphBindingSurface {
101 pub module_path: String,
102 pub name: String,
103 pub namespace: String,
104 pub visibility_kind: String,
105 pub visibility_scope: String,
106 pub origin_file: ProjectFile,
107 pub origin_module_path: String,
108 pub origin_name: String,
109 pub route_files: Vec<ProjectFile>,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub struct ImportGraphInputDigests {
116 pub binding_surface: [u8; 32],
117 pub import_rows: [u8; 32],
118}
119
120pub type ImportedFileEdgeTargets = HashMap<ProjectFile, Vec<Value>>;
122
123#[derive(Debug, Clone, PartialEq, Eq)]
127pub struct ImportedFileEdgeFacts {
128 pub import_ordinal: u32,
129 pub edges: ImportedFileEdgeTargets,
130}
131
132impl AdditionalFileDependencies {
133 pub fn complete(dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>) -> Self {
134 Self {
135 dependencies,
136 complete: true,
137 membership_cause: None,
138 }
139 }
140
141 pub fn incomplete(dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>) -> Self {
142 Self {
143 dependencies,
144 complete: false,
145 membership_cause: None,
146 }
147 }
148}
149
150impl<T: Any> CapabilityProvider for T {
151 fn as_any(&self) -> &dyn Any {
152 self
153 }
154}
155
156pub fn uncharged_imported_code_units(
158 build: impl FnOnce() -> HashSet<CodeUnit>,
159) -> Arc<crate::retention_budget::Accounted<HashSet<CodeUnit>>> {
160 Arc::new(crate::retention_budget::Accounted::uncharged(build()))
161}
162
163pub trait ImportAnalysisProvider: Send + Sync {
164 fn imported_code_units_of(
170 &self,
171 file: &ProjectFile,
172 ) -> Arc<crate::retention_budget::Accounted<HashSet<CodeUnit>>>;
173 fn referencing_files_of(&self, file: &ProjectFile) -> HashSet<ProjectFile>;
174
175 fn referencing_files_of_targets(
183 &self,
184 targets: &HashSet<ProjectFile>,
185 cancellation: &CancellationToken,
186 ) -> HashSet<ProjectFile> {
187 let mut referencing = HashSet::default();
188 for target in targets {
189 if cancellation.is_cancelled() {
190 break;
191 }
192 referencing.extend(self.referencing_files_of(target));
193 }
194 referencing
195 }
196
197 fn import_infos_for_files(
201 &self,
202 _files: &[ProjectFile],
203 ) -> Option<HashMap<ProjectFile, Vec<ImportInfo>>> {
204 None
205 }
206
207 fn file_dependency_facts_for_files(
214 &self,
215 files: &[ProjectFile],
216 ) -> Option<HashMap<ProjectFile, FileDependencyFacts>> {
217 self.import_infos_for_files(files).map(|infos| {
218 infos
219 .into_iter()
220 .map(|(file, imports)| {
221 (
222 file,
223 FileDependencyFacts {
224 imports,
225 contains_tests: None,
226 },
227 )
228 })
229 .collect()
230 })
231 }
232
233 fn has_complete_import_resolution_dependencies(&self) -> bool {
236 false
237 }
238
239 fn import_graph_module_path_keys_for_files(
243 &self,
244 _files: &[ProjectFile],
245 ) -> Option<HashMap<ProjectFile, Vec<String>>> {
246 None
247 }
248
249 fn import_graph_binding_surfaces_for_files(
253 &self,
254 _files: &[ProjectFile],
255 _cancellation: Option<&CancellationToken>,
256 ) -> Option<HashMap<ProjectFile, Vec<ImportGraphBindingSurface>>> {
257 None
258 }
259
260 fn import_graph_input_digests_for_files(
264 &self,
265 _files: &[ProjectFile],
266 _cancellation: Option<&CancellationToken>,
267 ) -> Option<HashMap<ProjectFile, ImportGraphInputDigests>> {
268 None
269 }
270
271 fn import_resolution_dependencies_for_files(
276 &self,
277 _files: &[ProjectFile],
278 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
279 _cancellation: Option<&CancellationToken>,
280 ) -> Option<HashMap<ProjectFile, ImportResolutionDependencies>> {
281 None
282 }
283
284 fn for_each_import_edge_facts_from_infos(
291 &self,
292 files: &[ProjectFile],
293 import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
294 selected_ordinals: &HashMap<ProjectFile, Vec<u32>>,
295 cancellation: Option<&CancellationToken>,
296 visit: &mut dyn FnMut(&ProjectFile, Vec<ImportedFileEdgeFacts>) -> bool,
297 ) -> Option<()> {
298 if !selected_ordinals.is_empty() {
299 return None;
300 }
301 self.for_each_imported_file_edges_from_infos(
302 files,
303 import_infos,
304 cancellation,
305 &mut |file, edges| {
306 visit(
307 file,
308 vec![ImportedFileEdgeFacts {
309 import_ordinal: u32::MAX,
310 edges,
311 }],
312 )
313 },
314 )
315 }
316
317 fn import_resolution_dependencies_for_ordinals(
321 &self,
322 files: &[ProjectFile],
323 import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
324 selected_ordinals: &HashMap<ProjectFile, Vec<u32>>,
325 cancellation: Option<&CancellationToken>,
326 ) -> Option<HashMap<ProjectFile, ImportResolutionDependencies>> {
327 if !selected_ordinals.is_empty() {
328 return None;
329 }
330 self.import_resolution_dependencies_for_files(files, import_infos, cancellation)
331 }
332
333 fn additional_direct_file_dependencies(
342 &self,
343 _files: &[ProjectFile],
344 _cancellation: &CancellationToken,
345 ) -> Option<AdditionalFileDependencies> {
346 Some(AdditionalFileDependencies::complete(HashMap::default()))
347 }
348
349 fn import_info_of(&self, _token: QueryToken<'_>, _file: &ProjectFile) -> Vec<ImportInfo> {
354 Vec::new()
355 }
356
357 fn import_info_of_checked(
365 &self,
366 _token: QueryToken<'_>,
367 _file: &ProjectFile,
368 ) -> Option<Vec<ImportInfo>> {
369 None
370 }
371
372 fn imported_code_units_from_infos(
375 &self,
376 _file: &ProjectFile,
377 _imports: &[ImportInfo],
378 ) -> Option<Arc<HashSet<CodeUnit>>> {
379 None
380 }
381
382 fn imported_files_from_infos(
386 &self,
387 _file: &ProjectFile,
388 _imports: &[ImportInfo],
389 ) -> Option<HashSet<ProjectFile>> {
390 None
391 }
392
393 fn imported_file_edge_provenance_from_infos(
398 &self,
399 _file: &ProjectFile,
400 _imports: &[ImportInfo],
401 ) -> Option<ImportedFileEdgeTargets> {
402 None
403 }
404
405 fn for_each_imported_files_from_infos(
411 &self,
412 _files: &[ProjectFile],
413 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
414 _cancellation: Option<&CancellationToken>,
415 _visit: &mut dyn FnMut(&ProjectFile, HashSet<ProjectFile>) -> bool,
416 ) -> Option<()> {
417 None
418 }
419
420 fn for_each_imported_file_edges_from_infos(
424 &self,
425 files: &[ProjectFile],
426 import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
427 cancellation: Option<&CancellationToken>,
428 visit: &mut dyn FnMut(&ProjectFile, ImportedFileEdgeTargets) -> bool,
429 ) -> Option<()> {
430 let mut visit_targets = |file: &ProjectFile, targets: HashSet<ProjectFile>| {
431 let facts = import_infos.and_then(|infos| infos.get(file)).map_or_else(
432 || serde_json::json!({ "kind": "provider_resolved_import_edge" }),
433 |imports| {
434 serde_json::json!({
435 "kind": "structured_import_facts",
436 "facts": imports
437 })
438 },
439 );
440 let edges = targets
441 .into_iter()
442 .map(|target| (target, vec![facts.clone()]))
443 .collect();
444 visit(file, edges)
445 };
446 self.for_each_imported_files_from_infos(
447 files,
448 import_infos,
449 cancellation,
450 &mut visit_targets,
451 )
452 }
453
454 fn relevant_imports_for(&self, _code_unit: &CodeUnit) -> HashSet<String> {
455 HashSet::default()
456 }
457
458 fn could_import_file(
464 &self,
465 _source_file: &ProjectFile,
466 _imports: &[ImportInfo],
467 _target: &ProjectFile,
468 ) -> bool {
469 false
470 }
471
472 fn prefetch_import_targets(
489 &self,
490 _files: &[ProjectFile],
491 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
492 _cancellation: &crate::cancellation::CancellationToken,
493 ) {
494 }
495
496 fn prefetch_file_dependency_targets(
504 &self,
505 _files: &[ProjectFile],
506 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
507 _cancellation: &crate::cancellation::CancellationToken,
508 ) {
509 }
510
511 fn import_reachability(
524 &self,
525 source_file: &ProjectFile,
526 imports: &[ImportInfo],
527 target: &ProjectFile,
528 ) -> ImportReachability {
529 if self.could_import_file(source_file, imports, target) {
530 ImportReachability::Reaches
531 } else {
532 ImportReachability::Unknown
533 }
534 }
535}
536
537#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552pub enum ImportReachability {
553 Reaches,
555 DoesNotReach,
557 Unknown,
560}
561
562pub fn resolve_imported_files_from_infos(
567 provider: &dyn ImportAnalysisProvider,
568 file: &ProjectFile,
569 imports: &[ImportInfo],
570) -> HashSet<ProjectFile> {
571 provider
572 .imported_files_from_infos(file, imports)
573 .unwrap_or_else(|| {
574 if let Some(units) = provider.imported_code_units_from_infos(file, imports) {
575 units.iter().map(|unit| unit.source().clone()).collect()
576 } else {
577 provider
578 .imported_code_units_of(file)
579 .iter()
580 .map(|unit| unit.source().clone())
581 .collect()
582 }
583 })
584}
585
586pub fn build_reverse_import_index<F>(
587 files: &[ProjectFile],
588 resolve_imported: F,
589 parallel: bool,
590) -> HashMap<ProjectFile, Arc<HashSet<ProjectFile>>>
591where
592 F: Fn(&ProjectFile) -> Arc<crate::retention_budget::Accounted<HashSet<CodeUnit>>> + Sync,
593{
594 build_reverse_file_index(
595 files,
596 |file| imported_source_files(&resolve_imported(file)),
597 parallel,
598 )
599}
600
601fn imported_source_files(imported: &HashSet<CodeUnit>) -> Vec<ProjectFile> {
602 imported
603 .iter()
604 .map(|code_unit| code_unit.source().clone())
605 .collect()
606}
607
608pub type ReverseFileIndex = HashMap<ProjectFile, Arc<HashSet<ProjectFile>>>;
609
610pub fn memoized_reverse_import_index<F, Files>(
611 memo: &PoolSafeMemo<ReverseFileIndex>,
612 files: Files,
613 resolve_imported: F,
614) -> Arc<ReverseFileIndex>
615where
616 F: Fn(&ProjectFile) -> Arc<crate::retention_budget::Accounted<HashSet<CodeUnit>>> + Sync + Copy,
617 Files: Fn() -> Vec<ProjectFile> + Copy,
618{
619 memoized_reverse_file_index(memo, files, |file| {
620 imported_source_files(&resolve_imported(file))
621 })
622}
623
624pub fn memoized_reverse_file_index<F, I, Files>(
625 memo: &PoolSafeMemo<ReverseFileIndex>,
626 files: Files,
627 resolve_targets: F,
628) -> Arc<ReverseFileIndex>
629where
630 F: Fn(&ProjectFile) -> I + Sync + Copy,
631 I: IntoIterator<Item = ProjectFile>,
632 Files: Fn() -> Vec<ProjectFile> + Copy,
633{
634 memo.get_or_build(
635 || {
636 let files = files();
637 build_reverse_file_index(&files, resolve_targets, true)
638 },
639 || {
640 let files = files();
641 build_reverse_file_index(&files, resolve_targets, false)
642 },
643 )
644}
645
646pub fn build_reverse_file_index<F, I>(
647 files: &[ProjectFile],
648 resolve_targets: F,
649 parallel: bool,
650) -> HashMap<ProjectFile, Arc<HashSet<ProjectFile>>>
651where
652 F: Fn(&ProjectFile) -> I + Sync,
653 I: IntoIterator<Item = ProjectFile>,
654{
655 let context = super::carried_context::CarriedContext::current();
656 let collect_edges = |file: &ProjectFile| {
657 context.run(|| {
658 let source = file.clone();
659 resolve_targets(file)
660 .into_iter()
661 .filter_map(move |target| (target != source).then(|| (target, source.clone())))
662 .collect::<Vec<_>>()
663 })
664 };
665 let edges: Vec<_> = if parallel {
666 files.par_iter().flat_map(collect_edges).collect()
667 } else {
668 files.iter().flat_map(collect_edges).collect()
669 };
670
671 let mut reverse: HashMap<ProjectFile, HashSet<ProjectFile>> = HashMap::default();
672 for (target, source) in edges {
673 reverse.entry(target).or_default().insert(source);
674 }
675 reverse
676 .into_iter()
677 .map(|(file, refs)| (file, Arc::new(refs)))
678 .collect()
679}
680
681pub trait TypeAliasProvider: CapabilityProvider + Send + Sync {
685 fn is_type_alias(&self, _code_unit: &CodeUnit) -> bool {
686 false
687 }
688}
689
690pub fn provider_declares_type_alias(
692 provider: Option<&dyn TypeAliasProvider>,
693 code_unit: &CodeUnit,
694) -> bool {
695 provider.is_some_and(|provider| provider.is_type_alias(code_unit))
696}
697
698pub trait TestDetectionProvider: CapabilityProvider {}
699
700#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
706pub enum DescendantIndexVariant {
707 WholeWorkspace,
709 ProductionOnly,
713}
714
715#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718pub struct SourceExclusionUnavailable;
719
720pub type SourceExclusionPredicate<'a> =
722 dyn Fn(&ProjectFile) -> Result<bool, SourceExclusionUnavailable> + 'a;
723
724#[derive(Clone, Copy)]
742pub struct DescendantIndexScope<'a> {
743 cancellation: &'a CancellationToken,
744 excluded_source: Option<&'a SourceExclusionPredicate<'a>>,
745}
746
747impl<'a> DescendantIndexScope<'a> {
748 pub fn whole_workspace(cancellation: &'a CancellationToken) -> Self {
750 Self {
751 cancellation,
752 excluded_source: None,
753 }
754 }
755
756 pub fn excluding_sources(
760 cancellation: &'a CancellationToken,
761 excluded: &'a SourceExclusionPredicate<'a>,
762 ) -> Self {
763 Self {
764 cancellation,
765 excluded_source: Some(excluded),
766 }
767 }
768
769 pub fn cancellation(&self) -> &'a CancellationToken {
770 self.cancellation
771 }
772
773 pub fn variant(&self) -> DescendantIndexVariant {
774 match self.excluded_source {
775 Some(_) => DescendantIndexVariant::ProductionOnly,
776 None => DescendantIndexVariant::WholeWorkspace,
777 }
778 }
779
780 pub fn keep_going(&self) -> impl Fn() -> bool + use<'_> {
783 || !self.cancellation.is_cancelled()
784 }
785
786 pub fn admits(&self, declaration: &CodeUnit) -> Result<bool, SourceExclusionUnavailable> {
788 match self.excluded_source {
789 Some(excluded) => excluded(declaration.source()).map(|excluded| !excluded),
790 None => Ok(true),
791 }
792 }
793}
794
795#[derive(Debug, Clone, Copy, PartialEq, Eq)]
797pub struct Cancelled;
798
799fn query_within_scope<T>(
800 scope: &DescendantIndexScope<'_>,
801 query: impl FnOnce() -> T,
802) -> Result<T, Cancelled> {
803 if scope.cancellation().is_cancelled() {
804 Err(Cancelled)
805 } else {
806 Ok(query())
807 }
808}
809
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
812pub struct PlatformInventoryMethod {
813 pub name: &'static str,
814 pub parameters: &'static [&'static str],
815 pub returns: &'static str,
816}
817
818#[derive(Debug)]
821pub struct ImplicitInterfaceMembers {
822 pub owner: &'static str,
823 pub simple_name: &'static str,
824 pub methods: Option<&'static [PlatformInventoryMethod]>,
827 pub declaration: Option<ImplicitMemberDeclarationRules>,
828}
829
830#[derive(Debug)]
834pub struct ImplicitMemberDeclarationRules {
835 pub visibility: crate::analyzer::structural::resolution::DeclaredVisibility,
836 pub is_abstract: bool,
837}
838
839#[derive(Debug, Clone, PartialEq, Eq)]
848pub enum MemberFamilyParameterType {
849 Primitive(String),
851 Nominal(String),
853 Unresolved(Vec<String>),
860 Array(Box<MemberFamilyParameterType>),
861 OwnerTypeParameter {
863 index: usize,
864 erasure: Box<MemberFamilyParameterType>,
865 },
866}
867
868#[derive(Debug, Clone, PartialEq, Eq)]
871pub enum MemberFamilySupertypeArguments {
872 Raw,
874 Arguments(Vec<MemberFamilyParameterType>),
875 Unknown,
877}
878
879#[derive(Debug, Clone, PartialEq, Eq)]
881pub struct UnreadMemberFamilyAncestor {
882 pub name: String,
883 pub inventory: Option<&'static [PlatformInventoryMethod]>,
884}
885
886#[derive(Debug, Default)]
887pub struct MemberFamilyAncestors {
888 pub resolved: Vec<CodeUnit>,
889 pub ambiguous: Vec<Vec<CodeUnit>>,
890 pub unread: Vec<UnreadMemberFamilyAncestor>,
891}
892
893#[derive(Debug, Clone, PartialEq, Eq)]
895pub enum HierarchyOpenReason {
896 MemberFamily(crate::analyzer::structural::resolution::MemberFamilyReason),
899 DescendantIndexUnavailable,
901 ForwardSatisfactionIncomplete,
904 UnreadAncestor(UnreadMemberFamilyAncestor),
906 OpenAncestorCandidates(Vec<CodeUnit>),
911 ExternalUnindexedAncestor {
918 name: String,
919 declared_by: CodeUnit,
920 may_name_indexed: bool,
921 },
922 SupertypesUnread { declared_by: CodeUnit },
925}
926
927impl HierarchyOpenReason {
928 pub fn description(&self) -> String {
930 match self {
931 Self::UnreadAncestor(ancestor) => format!("{}: {}", self.as_str(), ancestor.name),
932 Self::OpenAncestorCandidates(candidates) => {
933 let names: Vec<String> = candidates.iter().map(CodeUnit::fq_name).collect();
934 format!("{}: {}", self.as_str(), names.join(", "))
935 }
936 Self::ExternalUnindexedAncestor { name, .. } => format!("{}: {name}", self.as_str()),
937 _ => self.as_str().to_string(),
938 }
939 }
940
941 pub fn stopped_short(&self) -> bool {
946 matches!(
947 self,
948 Self::DescendantIndexUnavailable
949 | Self::MemberFamily(
950 crate::analyzer::structural::resolution::MemberFamilyReason::HierarchyTruncated
951 | crate::analyzer::structural::resolution::MemberFamilyReason::ProviderUnavailable
952 )
953 )
954 }
955
956 pub fn as_str(&self) -> &'static str {
958 match self {
959 Self::MemberFamily(reason) => reason.label(),
960 Self::DescendantIndexUnavailable => "descendant_index_unavailable",
961 Self::ForwardSatisfactionIncomplete => "forward_satisfaction_incomplete",
962 Self::UnreadAncestor(_) => "unread_ancestor",
963 Self::OpenAncestorCandidates(_) => "open_ancestor_candidates",
964 Self::ExternalUnindexedAncestor { .. } => {
965 crate::analyzer::structural::resolution::MemberFamilyReason::AncestorExternalUnindexed
966 .label()
967 }
968 Self::SupertypesUnread { .. } => "supertypes_unread",
969 }
970 }
971
972 pub fn declared_by(&self) -> Option<&CodeUnit> {
975 match self {
976 Self::ExternalUnindexedAncestor { declared_by, .. }
977 | Self::SupertypesUnread { declared_by } => Some(declared_by),
978 _ => None,
979 }
980 }
981
982 pub fn keeps_indexed_edges_exact(&self) -> bool {
987 matches!(
988 self,
989 Self::ExternalUnindexedAncestor {
990 may_name_indexed: false,
991 ..
992 }
993 )
994 }
995}
996
997#[derive(Debug, Clone, PartialEq, Eq)]
1003pub struct HierarchyAnswer<T = CodeUnit> {
1004 pub edges: Vec<T>,
1005 pub ambiguous: Vec<Vec<T>>,
1006 pub open: Vec<HierarchyOpenReason>,
1007}
1008
1009impl<T> HierarchyAnswer<T> {
1010 pub fn complete(edges: Vec<T>) -> Self {
1012 Self {
1013 edges,
1014 ambiguous: Vec::new(),
1015 open: Vec::new(),
1016 }
1017 }
1018
1019 pub fn incomplete(reason: HierarchyOpenReason) -> Self {
1021 Self {
1022 edges: Vec::new(),
1023 ambiguous: Vec::new(),
1024 open: vec![reason],
1025 }
1026 }
1027
1028 pub fn merge(&mut self, other: Self)
1030 where
1031 T: Ord,
1032 {
1033 self.edges.extend(other.edges);
1034 self.edges.sort();
1035 self.edges.dedup();
1036 self.ambiguous.extend(other.ambiguous);
1037 self.open.extend(other.open);
1038 }
1039
1040 pub fn is_complete(&self) -> bool {
1041 self.ambiguous.is_empty() && self.open.is_empty()
1042 }
1043
1044 pub fn stopped_short(&self) -> bool {
1046 self.open.iter().any(HierarchyOpenReason::stopped_short)
1047 }
1048
1049 pub fn keeps_indexed_edges_exact(&self) -> bool {
1053 self.ambiguous.is_empty()
1054 && self
1055 .open
1056 .iter()
1057 .all(HierarchyOpenReason::keeps_indexed_edges_exact)
1058 }
1059
1060 pub fn definite(&self) -> &[T] {
1063 &self.edges
1064 }
1065}
1066
1067pub trait HierarchyQuery {
1070 fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1071 fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1072 fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors;
1073
1074 fn direct_ancestors_within(
1075 &mut self,
1076 unit: &CodeUnit,
1077 scope: &DescendantIndexScope<'_>,
1078 ) -> Result<HierarchyAnswer, Cancelled> {
1079 query_within_scope(scope, || self.direct_ancestors(unit))
1080 }
1081
1082 fn direct_descendants_within(
1083 &mut self,
1084 unit: &CodeUnit,
1085 scope: &DescendantIndexScope<'_>,
1086 ) -> Result<HierarchyAnswer, Cancelled> {
1087 query_within_scope(scope, || self.direct_descendants(unit))
1088 }
1089}
1090
1091pub struct ForwardingHierarchyQuery<'a, P: ?Sized>(pub &'a P);
1094
1095impl<P: TypeHierarchyProvider + ?Sized> HierarchyQuery for ForwardingHierarchyQuery<'_, P> {
1096 fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1097 self.0.get_direct_ancestors(unit)
1098 }
1099 fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1100 self.0.get_direct_descendants(unit)
1101 }
1102 fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors {
1103 self.0.member_family_ancestors(unit)
1104 }
1105 fn direct_ancestors_within(
1106 &mut self,
1107 unit: &CodeUnit,
1108 scope: &DescendantIndexScope<'_>,
1109 ) -> Result<HierarchyAnswer, Cancelled> {
1110 self.0.get_direct_ancestors_within(unit, scope)
1111 }
1112 fn direct_descendants_within(
1113 &mut self,
1114 unit: &CodeUnit,
1115 scope: &DescendantIndexScope<'_>,
1116 ) -> Result<HierarchyAnswer, Cancelled> {
1117 self.0.get_direct_descendants_within(unit, scope)
1118 }
1119}
1120
1121pub trait TypeHierarchyProvider: Send + Sync {
1122 fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1124 run(&mut ForwardingHierarchyQuery(self));
1125 }
1126
1127 fn with_hierarchy_query_for(
1130 &self,
1131 _root: &CodeUnit,
1132 run: &mut dyn FnMut(&mut dyn HierarchyQuery),
1133 ) {
1134 self.with_hierarchy_query(run);
1135 }
1136
1137 fn get_direct_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1138 fn get_direct_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1139
1140 fn member_family_ancestors(&self, owner: &CodeUnit) -> MemberFamilyAncestors {
1146 let answer = self.get_direct_ancestors(owner);
1147 MemberFamilyAncestors {
1148 resolved: answer.edges,
1149 ambiguous: answer.ambiguous,
1150 unread: answer
1151 .open
1152 .into_iter()
1153 .filter_map(|reason| match reason {
1154 HierarchyOpenReason::ExternalUnindexedAncestor { name, .. } => {
1155 Some(UnreadMemberFamilyAncestor {
1156 name,
1157 inventory: None,
1158 })
1159 }
1160 _ => None,
1161 })
1162 .collect(),
1163 }
1164 }
1165
1166 fn member_family_inventory_matches(
1170 &self,
1171 member: &CodeUnit,
1172 inventory: &[PlatformInventoryMethod],
1173 ) -> bool {
1174 let methods: Vec<_> = inventory
1175 .iter()
1176 .filter(|method| method.name == member.identifier())
1177 .collect();
1178 if methods.is_empty() {
1179 return false;
1180 }
1181 let Some(arity) = self.member_family_parameter_arity(member) else {
1182 return true;
1183 };
1184 let methods: Vec<_> = methods
1185 .into_iter()
1186 .filter(|method| method.parameters.len() == arity)
1187 .collect();
1188 if methods.is_empty() {
1189 return false;
1190 }
1191 if methods.iter().any(|method| method.parameters.is_empty()) {
1192 return true;
1193 }
1194 let Some(parameters) = self.member_family_erased_parameters(member) else {
1195 return true;
1196 };
1197 methods.iter().any(|method| {
1198 parameters
1199 .iter()
1200 .map(String::as_str)
1201 .eq(method.parameters.iter().copied())
1202 })
1203 }
1204
1205 fn member_family_parameter_arity(&self, _member: &CodeUnit) -> Option<usize> {
1207 None
1208 }
1209
1210 fn member_family_erased_parameters(&self, _member: &CodeUnit) -> Option<Vec<String>> {
1213 None
1214 }
1215
1216 fn member_family_parameter_types(
1221 &self,
1222 _member: &CodeUnit,
1223 ) -> Option<Vec<MemberFamilyParameterType>> {
1224 None
1225 }
1226
1227 fn member_family_supertype_arguments(
1229 &self,
1230 _subtype: &CodeUnit,
1231 _supertype: &CodeUnit,
1232 ) -> MemberFamilySupertypeArguments {
1233 MemberFamilySupertypeArguments::Unknown
1234 }
1235
1236 fn supports_type_hierarchy(&self, code_unit: &CodeUnit) -> bool {
1237 code_unit.is_class()
1238 }
1239
1240 fn get_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1241 let mut result = None;
1242 self.with_hierarchy_query_for(code_unit, &mut |query| {
1243 result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1244 query.direct_ancestors(next)
1245 }));
1246 });
1247 result.expect("hierarchy query callback runs once")
1248 }
1249
1250 fn get_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1251 let mut result = None;
1252 self.with_hierarchy_query_for(code_unit, &mut |query| {
1253 result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1254 query.direct_descendants(next)
1255 }));
1256 });
1257 let mut answer = result.expect("hierarchy query callback runs once");
1258 answer.edges.sort();
1259 answer
1260 }
1261
1262 fn get_direct_ancestors_within(
1271 &self,
1272 code_unit: &CodeUnit,
1273 scope: &DescendantIndexScope<'_>,
1274 ) -> Result<HierarchyAnswer, Cancelled> {
1275 query_within_scope(scope, || self.get_direct_ancestors(code_unit))
1276 }
1277
1278 fn get_direct_descendants_within(
1297 &self,
1298 code_unit: &CodeUnit,
1299 scope: &DescendantIndexScope<'_>,
1300 ) -> Result<HierarchyAnswer, Cancelled> {
1301 query_within_scope(scope, || self.get_direct_descendants(code_unit))
1302 }
1303
1304 fn get_descendants_within(
1308 &self,
1309 code_unit: &CodeUnit,
1310 scope: &DescendantIndexScope<'_>,
1311 ) -> Result<HierarchyAnswer, Cancelled> {
1312 let mut result = None;
1313 self.with_hierarchy_query_for(code_unit, &mut |query| {
1314 result = Some(traverse_hierarchy_while(
1315 code_unit,
1316 query,
1317 scope.cancellation(),
1318 |query, next| query.direct_descendants_within(next, scope),
1319 ));
1320 });
1321 let mut answer = result.expect("hierarchy query callback runs once")?;
1322 answer.edges.sort();
1323 Ok(answer)
1324 }
1325
1326 fn get_polymorphic_matches<T: CodeUnitIndex>(
1327 &self,
1328 target: &CodeUnit,
1329 analyzer: &T,
1330 ) -> HierarchyAnswer
1331 where
1332 Self: Sized,
1333 {
1334 if !target.is_function() {
1335 return HierarchyAnswer::complete(Vec::new());
1336 }
1337
1338 let Some(parent) = analyzer.parent_of(target) else {
1339 return HierarchyAnswer::complete(Vec::new());
1340 };
1341
1342 self.get_descendants(&parent)
1343 }
1344}
1345
1346pub struct DirectDescendantIndex {
1354 nodes: Box<[CodeUnit]>,
1355 row_by_ancestor: HashMap<CodeUnit, u32>,
1356 descendants: CompactRows<u32>,
1357 open_candidates: Box<[CodeUnit]>,
1362}
1363
1364impl DirectDescendantIndex {
1365 pub fn estimated_retained_bytes(&self) -> usize {
1366 let node_bytes = self
1367 .nodes
1368 .iter()
1369 .map(|unit| {
1370 std::mem::size_of::<CodeUnit>()
1371 + unit.fq_name().len()
1372 + unit.signature().map_or(0, str::len)
1373 + unit.source().rel_path().as_os_str().len()
1374 + unit.source().root().as_os_str().len()
1375 })
1376 .sum::<usize>();
1377 std::mem::size_of::<Self>()
1378 + node_bytes * 2
1379 + self.row_by_ancestor.capacity()
1380 * (std::mem::size_of::<CodeUnit>() + std::mem::size_of::<u32>() + 1)
1381 + self.descendants.estimated_bytes() as usize
1382 + self
1383 .open_candidates
1384 .iter()
1385 .map(|unit| std::mem::size_of::<CodeUnit>() + unit.fq_name().len())
1386 .sum::<usize>()
1387 }
1388
1389 pub fn from_indexed_nodes(
1390 nodes: Vec<CodeUnit>,
1391 index_by_node: HashMap<CodeUnit, u32>,
1392 mut edges: Vec<(u32, u32)>,
1393 ) -> Self {
1394 normalize_indexed_edges(&nodes, &index_by_node, &mut edges);
1395
1396 let row_count = usize::from(!edges.is_empty())
1397 + edges
1398 .windows(2)
1399 .filter(|pair| pair[0].0 != pair[1].0)
1400 .count();
1401 let mut row_by_ancestor = HashMap::default();
1402 let mut descendants = CompactRowsBuilder::with_capacity(row_count, edges.len());
1403 let mut cursor = 0;
1404 while cursor < edges.len() {
1405 let ancestor = edges[cursor].0;
1406 let start = cursor;
1407 while cursor < edges.len() && edges[cursor].0 == ancestor {
1408 cursor += 1;
1409 }
1410 let row =
1411 u32::try_from(descendants.rows()).expect("hierarchy index rows must fit in a u32");
1412 row_by_ancestor.insert(nodes[ancestor as usize].clone(), row);
1413 descendants.push_row(
1414 edges[start..cursor]
1415 .iter()
1416 .map(|(_, descendant)| *descendant),
1417 );
1418 }
1419 Self {
1420 nodes: nodes.into_boxed_slice(),
1421 row_by_ancestor,
1422 descendants: descendants.finish(),
1423 open_candidates: Box::default(),
1424 }
1425 }
1426
1427 pub fn with_open_candidates(mut self, mut open_candidates: Vec<CodeUnit>) -> Self {
1429 open_candidates.sort();
1430 open_candidates.dedup();
1431 self.open_candidates = open_candidates.into_boxed_slice();
1432 self
1433 }
1434
1435 pub fn nodes(&self) -> &[CodeUnit] {
1438 &self.nodes
1439 }
1440
1441 pub fn open_candidates(&self) -> &[CodeUnit] {
1442 &self.open_candidates
1443 }
1444
1445 pub fn answer(&self, ancestor: &CodeUnit) -> HierarchyAnswer {
1448 let mut edges: Vec<_> = self.descendants(ancestor).into_iter().collect();
1449 edges.sort();
1450 let mut answer = HierarchyAnswer::complete(edges);
1451 let open_candidates: Vec<_> = self
1452 .open_candidates
1453 .iter()
1454 .filter(|candidate| *candidate != ancestor)
1455 .cloned()
1456 .collect();
1457 if !open_candidates.is_empty() {
1458 answer
1459 .open
1460 .push(HierarchyOpenReason::OpenAncestorCandidates(open_candidates));
1461 }
1462 answer
1463 }
1464
1465 pub fn descendants(&self, ancestor: &CodeUnit) -> HashSet<CodeUnit> {
1466 let Some(row) = self.row_by_ancestor.get(ancestor).copied() else {
1467 return HashSet::default();
1468 };
1469 self.descendants
1470 .row(row as usize)
1471 .iter()
1472 .map(|descendant| self.nodes[*descendant as usize].clone())
1473 .collect()
1474 }
1475}
1476
1477pub fn build_direct_descendant_index<A, P>(
1486 analyzer: &A,
1487 provider: &P,
1488 scope: &DescendantIndexScope<'_>,
1489) -> Option<DirectDescendantIndex>
1490where
1491 A: CodeUnitIndex,
1492 P: TypeHierarchyProvider + ?Sized,
1493{
1494 let mut result = None;
1495 provider.with_hierarchy_query(&mut |query| {
1496 result = Some(build_direct_descendant_index_in_query(
1497 analyzer, query, scope,
1498 ));
1499 });
1500 result.expect("hierarchy query callback runs once")
1501}
1502
1503pub fn build_direct_descendant_index_in_query<A: CodeUnitIndex>(
1505 analyzer: &A,
1506 query: &mut dyn HierarchyQuery,
1507 scope: &DescendantIndexScope<'_>,
1508) -> Option<DirectDescendantIndex> {
1509 let mut candidates = Vec::new();
1510 for candidate in analyzer.all_declarations().filter(CodeUnit::is_class) {
1511 if match scope.admits(&candidate) {
1512 Ok(value) => value,
1513 Err(reason) => {
1514 let _unavailable = reason;
1515 return None;
1516 }
1517 } {
1518 candidates.push(candidate);
1519 }
1520 }
1521 build_direct_descendant_index_from_candidates(
1522 candidates,
1523 |candidate| query.direct_ancestors_within(candidate, scope).ok(),
1524 &scope.keep_going(),
1525 )
1526}
1527
1528pub fn build_direct_descendant_index_from_candidates<F>(
1542 mut candidates: Vec<CodeUnit>,
1543 mut direct_ancestors: F,
1544 keep_going: &dyn Fn() -> bool,
1545) -> Option<DirectDescendantIndex>
1546where
1547 F: FnMut(&CodeUnit) -> Option<HierarchyAnswer>,
1548{
1549 candidates.sort();
1550 candidates.dedup();
1551 let mut types_by_fq_name: HashMap<String, Vec<CodeUnit>> = HashMap::default();
1552 for candidate in &candidates {
1553 types_by_fq_name
1554 .entry(candidate.fq_name())
1555 .or_default()
1556 .push(candidate.clone());
1557 }
1558 let mut nodes = candidates.clone();
1559 let mut index_by_node: HashMap<_, _> = nodes
1560 .iter()
1561 .enumerate()
1562 .map(|(index, node)| {
1563 (
1564 node.clone(),
1565 u32::try_from(index).expect("hierarchy index declarations must fit in a u32"),
1566 )
1567 })
1568 .collect();
1569 let mut edges = Vec::new();
1570 let mut open_candidates = Vec::new();
1571 for candidate in candidates {
1572 if !keep_going() {
1573 return None;
1574 }
1575 let descendant = index_by_node[&candidate];
1576 let answer = direct_ancestors(&candidate)?;
1577 if !answer.keeps_indexed_edges_exact() {
1581 open_candidates.push(candidate.clone());
1582 }
1583 for ancestor in answer.edges {
1584 let ancestor = types_by_fq_name
1585 .get(&ancestor.fq_name())
1586 .and_then(|same_name| {
1587 let mut same_source = same_name
1588 .iter()
1589 .filter(|unit| unit.source() == candidate.source());
1590 let exact = same_source.next()?;
1591 same_source.next().is_none().then(|| exact.clone())
1592 })
1593 .unwrap_or(ancestor);
1594 let ancestor = *index_by_node.entry(ancestor.clone()).or_insert_with(|| {
1595 let index = u32::try_from(nodes.len())
1596 .expect("hierarchy index declarations must fit in a u32");
1597 nodes.push(ancestor);
1598 index
1599 });
1600 edges.push((ancestor, descendant));
1601 }
1602 }
1603 Some(
1604 DirectDescendantIndex::from_indexed_nodes(nodes, index_by_node, edges)
1605 .with_open_candidates(open_candidates),
1606 )
1607}
1608
1609fn traverse_hierarchy(
1610 root: &CodeUnit,
1611 query: &mut dyn HierarchyQuery,
1612 mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> HierarchyAnswer,
1613) -> HierarchyAnswer {
1614 traverse_hierarchy_edges(root, |unit| next(query, unit))
1615}
1616
1617fn traverse_hierarchy_while(
1618 root: &CodeUnit,
1619 query: &mut dyn HierarchyQuery,
1620 cancellation: &CancellationToken,
1621 mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1622) -> Result<HierarchyAnswer, Cancelled> {
1623 traverse_hierarchy_edges_while(root, cancellation, |unit| next(query, unit))
1624}
1625
1626fn traverse_hierarchy_edges_while<F>(
1631 root: &CodeUnit,
1632 cancellation: &CancellationToken,
1633 mut next: F,
1634) -> Result<HierarchyAnswer, Cancelled>
1635where
1636 F: FnMut(&CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1637{
1638 let mut result = HierarchyAnswer::complete(Vec::new());
1639 let mut seen = BTreeSet::new();
1640 let mut queue = VecDeque::from([root.clone()]);
1641 while let Some(current) = queue.pop_front() {
1642 let answer = next(¤t)?;
1643 result.ambiguous.extend(answer.ambiguous);
1644 for reason in answer.open {
1645 if let HierarchyOpenReason::OpenAncestorCandidates(candidates) = &reason
1648 && result.open.iter().any(|seen| {
1649 matches!(seen, HierarchyOpenReason::OpenAncestorCandidates(other) if other == candidates)
1650 })
1651 {
1652 continue;
1653 }
1654 result.open.push(reason);
1655 }
1656 for item in answer.edges {
1657 if seen.insert(item.fq_name()) {
1658 queue.push_back(item.clone());
1659 result.edges.push(item);
1660 }
1661 }
1662 if !queue.is_empty() && cancellation.is_cancelled() {
1663 return Err(Cancelled);
1664 }
1665 }
1666 Ok(result)
1667}
1668
1669fn traverse_hierarchy_edges<F>(root: &CodeUnit, mut next: F) -> HierarchyAnswer
1670where
1671 F: FnMut(&CodeUnit) -> HierarchyAnswer,
1672{
1673 traverse_hierarchy_edges_while(root, &CancellationToken::new(), |unit| Ok(next(unit)))
1676 .expect("unscoped hierarchy traversal cannot stop")
1677}
1678
1679#[cfg(test)]
1680mod hierarchy_traversal_properties {
1681 use super::*;
1682 use crate::analyzer::model::CodeUnitType;
1683 use proptest::prelude::*;
1684 use std::collections::BTreeMap;
1685
1686 const NODES: usize = 8;
1687
1688 fn node(index: usize) -> CodeUnit {
1689 CodeUnit::new(
1690 ProjectFile::new(std::env::temp_dir(), "Hierarchy.java"),
1691 CodeUnitType::Class,
1692 "",
1693 format!("N{index}"),
1694 )
1695 }
1696
1697 #[test]
1698 fn transitive_walks_borrow_one_query_and_preserve_scoped_dispatch() {
1699 use std::sync::atomic::{AtomicUsize, Ordering};
1700 struct Provider(AtomicUsize);
1701 struct Query;
1702 impl HierarchyQuery for Query {
1703 fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1704 let index = index_of(unit);
1705 HierarchyAnswer::complete(if index < 2 {
1706 vec![node(index + 1)]
1707 } else {
1708 Vec::new()
1709 })
1710 }
1711 fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1712 self.direct_ancestors(unit)
1713 }
1714 fn member_family_ancestors(&mut self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1715 MemberFamilyAncestors::default()
1716 }
1717 fn direct_descendants_within(
1718 &mut self,
1719 _unit: &CodeUnit,
1720 _scope: &DescendantIndexScope<'_>,
1721 ) -> Result<HierarchyAnswer, Cancelled> {
1722 Err(Cancelled)
1723 }
1724 }
1725 impl TypeHierarchyProvider for Provider {
1726 fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1727 panic!("the walk must use its query")
1728 }
1729 fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1730 panic!("the walk must use its query")
1731 }
1732 fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1733 self.0.fetch_add(1, Ordering::Relaxed);
1734 run(&mut Query);
1735 }
1736 }
1737 let provider = Provider(AtomicUsize::new(0));
1738 assert_eq!(
1739 provider.get_ancestors(&node(0)).edges,
1740 vec![node(1), node(2)]
1741 );
1742 assert_eq!(provider.0.load(Ordering::Relaxed), 1);
1743 assert_eq!(
1744 provider.get_descendants(&node(0)).edges,
1745 vec![node(1), node(2)]
1746 );
1747 assert_eq!(provider.0.load(Ordering::Relaxed), 2);
1748 let cancellation = CancellationToken::new();
1749 assert!(
1750 provider
1751 .get_descendants_within(
1752 &node(0),
1753 &DescendantIndexScope::whole_workspace(&cancellation)
1754 )
1755 .is_err()
1756 );
1757 assert_eq!(provider.0.load(Ordering::Relaxed), 3);
1758 }
1759
1760 #[test]
1761 fn default_query_forwards_scoped_provider_overrides() {
1762 struct Provider;
1763 impl TypeHierarchyProvider for Provider {
1764 fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1765 HierarchyAnswer::complete(vec![node(1)])
1766 }
1767 fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1768 HierarchyAnswer::complete(vec![node(2)])
1769 }
1770 fn get_direct_ancestors_within(
1771 &self,
1772 _unit: &CodeUnit,
1773 _scope: &DescendantIndexScope<'_>,
1774 ) -> Result<HierarchyAnswer, Cancelled> {
1775 Err(Cancelled)
1776 }
1777 fn member_family_ancestors(&self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1778 MemberFamilyAncestors {
1779 resolved: vec![node(3)],
1780 ..Default::default()
1781 }
1782 }
1783 }
1784 let cancellation = CancellationToken::new();
1785 Provider.with_hierarchy_query(&mut |query| {
1786 assert_eq!(query.direct_ancestors(&node(0)).edges, vec![node(1)]);
1787 assert_eq!(query.direct_descendants(&node(0)).edges, vec![node(2)]);
1788 assert_eq!(
1789 query.member_family_ancestors(&node(0)).resolved,
1790 vec![node(3)]
1791 );
1792 assert!(
1793 query
1794 .direct_ancestors_within(
1795 &node(0),
1796 &DescendantIndexScope::whole_workspace(&cancellation)
1797 )
1798 .is_err()
1799 );
1800 });
1801 }
1802
1803 fn index_of(unit: &CodeUnit) -> usize {
1804 unit.fq_name()[1..].parse().expect("test node name")
1805 }
1806
1807 #[test]
1808 fn closure_preserves_uncertainty_without_traversing_alternatives() {
1809 let mut visited = Vec::new();
1810 let answer = traverse_hierarchy_edges(&node(0), |unit| {
1811 let id = index_of(unit);
1812 visited.push(id);
1813 match id {
1814 0 => HierarchyAnswer {
1815 edges: vec![node(1), node(1)],
1816 ambiguous: vec![vec![node(2), node(3)]],
1817 open: Vec::new(),
1818 },
1819 1 => HierarchyAnswer {
1820 edges: Vec::new(),
1821 ambiguous: vec![vec![node(4), node(5)]],
1822 open: vec![HierarchyOpenReason::UnreadAncestor(
1823 UnreadMemberFamilyAncestor {
1824 name: "External".into(),
1825 inventory: None,
1826 },
1827 )],
1828 },
1829 _ => panic!("ambiguous alternatives must not be traversed"),
1830 }
1831 });
1832 assert_eq!(visited, vec![0, 1]);
1833 assert_eq!(answer.edges, vec![node(1)]);
1834 assert_eq!(
1835 answer.ambiguous,
1836 vec![vec![node(2), node(3)], vec![node(4), node(5)]]
1837 );
1838 assert!(
1839 matches!(answer.open.as_slice(), [HierarchyOpenReason::UnreadAncestor(ancestor)] if ancestor.name == "External")
1840 );
1841 assert!(!answer.is_complete());
1842 }
1843
1844 #[test]
1845 #[brokk_bifrost_test_macros::hardwon(
1846 "#12211: an open candidate tainted its own descendant answer"
1847 )]
1848 #[brokk_bifrost_test_macros::hardwon(
1849 "#12172: an open candidate's own ancestry tainted its descendant query"
1850 )]
1851 fn an_open_candidate_does_not_taint_its_own_descendants() {
1852 let project = ProjectFile::new(std::env::temp_dir(), "Hierarchy.java");
1853 let class = |name: &str| CodeUnit::new(project.clone(), CodeUnitType::Class, "", name);
1854 let base = class("Base");
1855 let open = class("Open");
1856 let derived = class("Derived");
1857 let index = build_direct_descendant_index_from_candidates(
1858 vec![base.clone(), open.clone(), derived.clone()],
1859 |candidate| {
1860 if candidate == &open {
1861 Some(HierarchyAnswer {
1862 edges: vec![base.clone()],
1863 open: vec![HierarchyOpenReason::UnreadAncestor(
1864 UnreadMemberFamilyAncestor {
1865 name: "Mystery".into(),
1866 inventory: None,
1867 },
1868 )],
1869 ambiguous: Vec::new(),
1870 })
1871 } else if candidate == &derived {
1872 Some(HierarchyAnswer::complete(vec![open.clone()]))
1873 } else {
1874 Some(HierarchyAnswer::complete(Vec::new()))
1875 }
1876 },
1877 &|| true,
1878 )
1879 .expect("finished open answers build an index");
1880
1881 let base_answer = index.answer(&base);
1882 assert!(!base_answer.is_complete());
1883 assert!(matches!(
1884 base_answer.open.as_slice(),
1885 [HierarchyOpenReason::OpenAncestorCandidates(candidates)]
1886 if candidates == std::slice::from_ref(&open)
1887 ));
1888
1889 let own = index.answer(&open);
1890 assert!(own.is_complete(), "{own:?}");
1891 assert_eq!(own.edges, vec![derived]);
1892 }
1893
1894 fn graphs() -> impl Strategy<Value = Vec<Vec<usize>>> {
1896 proptest::collection::vec(proptest::collection::vec(0..NODES, 0..5), NODES)
1897 }
1898
1899 fn reference_distances(graph: &[Vec<usize>], root: usize) -> BTreeMap<usize, usize> {
1903 let mut distance: BTreeMap<usize, usize> = BTreeMap::new();
1904 for &next in &graph[root] {
1905 distance.insert(next, 1);
1906 }
1907 loop {
1908 let mut changed = false;
1909 for (from, edges) in graph.iter().enumerate() {
1910 let Some(&base) = distance.get(&from) else {
1911 continue;
1912 };
1913 for &to in edges {
1914 if distance.get(&to).is_none_or(|&known| known > base + 1) {
1915 distance.insert(to, base + 1);
1916 changed = true;
1917 }
1918 }
1919 }
1920 if !changed {
1921 return distance;
1922 }
1923 }
1924 }
1925
1926 proptest! {
1927 #![proptest_config(ProptestConfig::with_cases(128))]
1928
1929 #[test]
1934 fn visits_exactly_the_reachable_set_once_in_breadth_first_order(
1935 graph in graphs(),
1936 root in 0..NODES,
1937 ) {
1938 let mut calls: BTreeMap<usize, usize> = BTreeMap::new();
1939 let result = traverse_hierarchy_edges(&node(root), |unit| {
1940 let id = index_of(unit);
1941 *calls.entry(id).or_default() += 1;
1942 HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())
1943 });
1944 let found: Vec<usize> = result.edges.iter().map(index_of).collect();
1945
1946 let distance = reference_distances(&graph, root);
1947 let unique: BTreeSet<usize> = found.iter().copied().collect();
1948 prop_assert_eq!(found.len(), unique.len(), "a declaration was returned twice: {:?}", found);
1949 prop_assert_eq!(unique, distance.keys().copied().collect::<BTreeSet<_>>());
1950 prop_assert!(
1951 found.windows(2).all(|pair| distance[&pair[0]] <= distance[&pair[1]]),
1952 "not breadth-first: {:?} with distances {:?}", found, distance
1953 );
1954 prop_assert!(
1957 calls.iter().all(|(&id, &count)| count == 1 || (id == root && count == 2)),
1958 "repeated expansion: {:?}", calls
1959 );
1960
1961 let live = CancellationToken::new();
1963 let guarded = traverse_hierarchy_edges_while(&node(root), &live, |unit| {
1964 Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1965 });
1966 let guarded = guarded.expect("live traversal");
1967 prop_assert!(guarded.is_complete());
1968 prop_assert_eq!(guarded.edges, result.edges);
1969 }
1970
1971 #[test]
1975 fn guarded_traversal_never_returns_a_partial_answer(
1976 graph in graphs(),
1977 root in 0..NODES,
1978 fail_on in 0..NODES,
1979 ) {
1980 let reachable = reference_distances(&graph, root);
1981 let failing = traverse_hierarchy_edges_while(&node(root), &CancellationToken::new(), |unit| {
1982 let id = index_of(unit);
1983 if id == fail_on { Err(Cancelled) } else { Ok(HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())) }
1984 });
1985 let requested = fail_on == root || reachable.contains_key(&fail_on);
1988 prop_assert_eq!(failing.is_err(), requested);
1989
1990 let cancelled = CancellationToken::new();
1991 cancelled.cancel();
1992 let stopped = traverse_hierarchy_edges_while(&node(root), &cancelled, |unit| {
1993 Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1994 });
1995 prop_assert_eq!(stopped.is_err(), !graph[root].is_empty());
1996 if graph[root].is_empty() {
1997 let stopped = stopped.expect("empty traversal");
1998 prop_assert!(stopped.is_complete());
1999 prop_assert!(stopped.edges.is_empty());
2000 }
2001 }
2002 }
2003}