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, Clone, PartialEq, Eq)]
827pub enum MemberFamilyParameterType {
828 Primitive(String),
830 Nominal(String),
832 Unresolved(Vec<String>),
839 Array(Box<MemberFamilyParameterType>),
840 OwnerTypeParameter {
842 index: usize,
843 erasure: Box<MemberFamilyParameterType>,
844 },
845}
846
847#[derive(Debug, Clone, PartialEq, Eq)]
850pub enum MemberFamilySupertypeArguments {
851 Raw,
853 Arguments(Vec<MemberFamilyParameterType>),
854 Unknown,
856}
857
858#[derive(Debug, Clone, PartialEq, Eq)]
860pub struct UnreadMemberFamilyAncestor {
861 pub name: String,
862 pub inventory: Option<&'static [PlatformInventoryMethod]>,
863}
864
865#[derive(Debug, Default)]
866pub struct MemberFamilyAncestors {
867 pub resolved: Vec<CodeUnit>,
868 pub ambiguous: Vec<Vec<CodeUnit>>,
869 pub unread: Vec<UnreadMemberFamilyAncestor>,
870}
871
872#[derive(Debug, Clone, PartialEq, Eq)]
874pub enum HierarchyOpenReason {
875 MemberFamily(crate::analyzer::structural::resolution::MemberFamilyReason),
878 DescendantIndexUnavailable,
880 ForwardSatisfactionIncomplete,
883 UnreadAncestor(UnreadMemberFamilyAncestor),
885 OpenAncestorCandidates(Vec<CodeUnit>),
890 ExternalUnindexedAncestor {
897 name: String,
898 declared_by: CodeUnit,
899 may_name_indexed: bool,
900 },
901 SupertypesUnread { declared_by: CodeUnit },
904}
905
906impl HierarchyOpenReason {
907 pub fn description(&self) -> String {
909 match self {
910 Self::UnreadAncestor(ancestor) => format!("{}: {}", self.as_str(), ancestor.name),
911 Self::OpenAncestorCandidates(candidates) => {
912 let names: Vec<String> = candidates.iter().map(CodeUnit::fq_name).collect();
913 format!("{}: {}", self.as_str(), names.join(", "))
914 }
915 Self::ExternalUnindexedAncestor { name, .. } => format!("{}: {name}", self.as_str()),
916 _ => self.as_str().to_string(),
917 }
918 }
919
920 pub fn stopped_short(&self) -> bool {
925 matches!(
926 self,
927 Self::DescendantIndexUnavailable
928 | Self::MemberFamily(
929 crate::analyzer::structural::resolution::MemberFamilyReason::HierarchyTruncated
930 | crate::analyzer::structural::resolution::MemberFamilyReason::ProviderUnavailable
931 )
932 )
933 }
934
935 pub fn as_str(&self) -> &'static str {
937 match self {
938 Self::MemberFamily(reason) => reason.label(),
939 Self::DescendantIndexUnavailable => "descendant_index_unavailable",
940 Self::ForwardSatisfactionIncomplete => "forward_satisfaction_incomplete",
941 Self::UnreadAncestor(_) => "unread_ancestor",
942 Self::OpenAncestorCandidates(_) => "open_ancestor_candidates",
943 Self::ExternalUnindexedAncestor { .. } => {
944 crate::analyzer::structural::resolution::MemberFamilyReason::AncestorExternalUnindexed
945 .label()
946 }
947 Self::SupertypesUnread { .. } => "supertypes_unread",
948 }
949 }
950
951 pub fn declared_by(&self) -> Option<&CodeUnit> {
954 match self {
955 Self::ExternalUnindexedAncestor { declared_by, .. }
956 | Self::SupertypesUnread { declared_by } => Some(declared_by),
957 _ => None,
958 }
959 }
960
961 pub fn keeps_indexed_edges_exact(&self) -> bool {
966 matches!(
967 self,
968 Self::ExternalUnindexedAncestor {
969 may_name_indexed: false,
970 ..
971 }
972 )
973 }
974}
975
976#[derive(Debug, Clone, PartialEq, Eq)]
982pub struct HierarchyAnswer<T = CodeUnit> {
983 pub edges: Vec<T>,
984 pub ambiguous: Vec<Vec<T>>,
985 pub open: Vec<HierarchyOpenReason>,
986}
987
988impl<T> HierarchyAnswer<T> {
989 pub fn complete(edges: Vec<T>) -> Self {
991 Self {
992 edges,
993 ambiguous: Vec::new(),
994 open: Vec::new(),
995 }
996 }
997
998 pub fn incomplete(reason: HierarchyOpenReason) -> Self {
1000 Self {
1001 edges: Vec::new(),
1002 ambiguous: Vec::new(),
1003 open: vec![reason],
1004 }
1005 }
1006
1007 pub fn merge(&mut self, other: Self)
1009 where
1010 T: Ord,
1011 {
1012 self.edges.extend(other.edges);
1013 self.edges.sort();
1014 self.edges.dedup();
1015 self.ambiguous.extend(other.ambiguous);
1016 self.open.extend(other.open);
1017 }
1018
1019 pub fn is_complete(&self) -> bool {
1020 self.ambiguous.is_empty() && self.open.is_empty()
1021 }
1022
1023 pub fn stopped_short(&self) -> bool {
1025 self.open.iter().any(HierarchyOpenReason::stopped_short)
1026 }
1027
1028 pub fn keeps_indexed_edges_exact(&self) -> bool {
1032 self.ambiguous.is_empty()
1033 && self
1034 .open
1035 .iter()
1036 .all(HierarchyOpenReason::keeps_indexed_edges_exact)
1037 }
1038
1039 pub fn definite(&self) -> &[T] {
1042 &self.edges
1043 }
1044}
1045
1046pub trait HierarchyQuery {
1049 fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1050 fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1051 fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors;
1052
1053 fn direct_ancestors_within(
1054 &mut self,
1055 unit: &CodeUnit,
1056 scope: &DescendantIndexScope<'_>,
1057 ) -> Result<HierarchyAnswer, Cancelled> {
1058 query_within_scope(scope, || self.direct_ancestors(unit))
1059 }
1060
1061 fn direct_descendants_within(
1062 &mut self,
1063 unit: &CodeUnit,
1064 scope: &DescendantIndexScope<'_>,
1065 ) -> Result<HierarchyAnswer, Cancelled> {
1066 query_within_scope(scope, || self.direct_descendants(unit))
1067 }
1068}
1069
1070pub struct ForwardingHierarchyQuery<'a, P: ?Sized>(pub &'a P);
1073
1074impl<P: TypeHierarchyProvider + ?Sized> HierarchyQuery for ForwardingHierarchyQuery<'_, P> {
1075 fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1076 self.0.get_direct_ancestors(unit)
1077 }
1078 fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1079 self.0.get_direct_descendants(unit)
1080 }
1081 fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors {
1082 self.0.member_family_ancestors(unit)
1083 }
1084 fn direct_ancestors_within(
1085 &mut self,
1086 unit: &CodeUnit,
1087 scope: &DescendantIndexScope<'_>,
1088 ) -> Result<HierarchyAnswer, Cancelled> {
1089 self.0.get_direct_ancestors_within(unit, scope)
1090 }
1091 fn direct_descendants_within(
1092 &mut self,
1093 unit: &CodeUnit,
1094 scope: &DescendantIndexScope<'_>,
1095 ) -> Result<HierarchyAnswer, Cancelled> {
1096 self.0.get_direct_descendants_within(unit, scope)
1097 }
1098}
1099
1100pub trait TypeHierarchyProvider: Send + Sync {
1101 fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1103 run(&mut ForwardingHierarchyQuery(self));
1104 }
1105
1106 fn with_hierarchy_query_for(
1109 &self,
1110 _root: &CodeUnit,
1111 run: &mut dyn FnMut(&mut dyn HierarchyQuery),
1112 ) {
1113 self.with_hierarchy_query(run);
1114 }
1115
1116 fn get_direct_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1117 fn get_direct_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1118
1119 fn member_family_ancestors(&self, owner: &CodeUnit) -> MemberFamilyAncestors {
1125 let answer = self.get_direct_ancestors(owner);
1126 MemberFamilyAncestors {
1127 resolved: answer.edges,
1128 ambiguous: answer.ambiguous,
1129 unread: answer
1130 .open
1131 .into_iter()
1132 .filter_map(|reason| match reason {
1133 HierarchyOpenReason::ExternalUnindexedAncestor { name, .. } => {
1134 Some(UnreadMemberFamilyAncestor {
1135 name,
1136 inventory: None,
1137 })
1138 }
1139 _ => None,
1140 })
1141 .collect(),
1142 }
1143 }
1144
1145 fn member_family_inventory_matches(
1149 &self,
1150 member: &CodeUnit,
1151 inventory: &[PlatformInventoryMethod],
1152 ) -> bool {
1153 let methods: Vec<_> = inventory
1154 .iter()
1155 .filter(|method| method.name == member.identifier())
1156 .collect();
1157 if methods.is_empty() {
1158 return false;
1159 }
1160 let Some(arity) = self.member_family_parameter_arity(member) else {
1161 return true;
1162 };
1163 let methods: Vec<_> = methods
1164 .into_iter()
1165 .filter(|method| method.parameters.len() == arity)
1166 .collect();
1167 if methods.is_empty() {
1168 return false;
1169 }
1170 if methods.iter().any(|method| method.parameters.is_empty()) {
1171 return true;
1172 }
1173 let Some(parameters) = self.member_family_erased_parameters(member) else {
1174 return true;
1175 };
1176 methods.iter().any(|method| {
1177 parameters
1178 .iter()
1179 .map(String::as_str)
1180 .eq(method.parameters.iter().copied())
1181 })
1182 }
1183
1184 fn member_family_parameter_arity(&self, _member: &CodeUnit) -> Option<usize> {
1186 None
1187 }
1188
1189 fn member_family_erased_parameters(&self, _member: &CodeUnit) -> Option<Vec<String>> {
1192 None
1193 }
1194
1195 fn member_family_parameter_types(
1200 &self,
1201 _member: &CodeUnit,
1202 ) -> Option<Vec<MemberFamilyParameterType>> {
1203 None
1204 }
1205
1206 fn member_family_supertype_arguments(
1208 &self,
1209 _subtype: &CodeUnit,
1210 _supertype: &CodeUnit,
1211 ) -> MemberFamilySupertypeArguments {
1212 MemberFamilySupertypeArguments::Unknown
1213 }
1214
1215 fn supports_type_hierarchy(&self, code_unit: &CodeUnit) -> bool {
1216 code_unit.is_class()
1217 }
1218
1219 fn get_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1220 let mut result = None;
1221 self.with_hierarchy_query_for(code_unit, &mut |query| {
1222 result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1223 query.direct_ancestors(next)
1224 }));
1225 });
1226 result.expect("hierarchy query callback runs once")
1227 }
1228
1229 fn get_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1230 let mut result = None;
1231 self.with_hierarchy_query_for(code_unit, &mut |query| {
1232 result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1233 query.direct_descendants(next)
1234 }));
1235 });
1236 let mut answer = result.expect("hierarchy query callback runs once");
1237 answer.edges.sort();
1238 answer
1239 }
1240
1241 fn get_direct_ancestors_within(
1250 &self,
1251 code_unit: &CodeUnit,
1252 scope: &DescendantIndexScope<'_>,
1253 ) -> Result<HierarchyAnswer, Cancelled> {
1254 query_within_scope(scope, || self.get_direct_ancestors(code_unit))
1255 }
1256
1257 fn get_direct_descendants_within(
1276 &self,
1277 code_unit: &CodeUnit,
1278 scope: &DescendantIndexScope<'_>,
1279 ) -> Result<HierarchyAnswer, Cancelled> {
1280 query_within_scope(scope, || self.get_direct_descendants(code_unit))
1281 }
1282
1283 fn get_descendants_within(
1287 &self,
1288 code_unit: &CodeUnit,
1289 scope: &DescendantIndexScope<'_>,
1290 ) -> Result<HierarchyAnswer, Cancelled> {
1291 let mut result = None;
1292 self.with_hierarchy_query_for(code_unit, &mut |query| {
1293 result = Some(traverse_hierarchy_while(
1294 code_unit,
1295 query,
1296 scope.cancellation(),
1297 |query, next| query.direct_descendants_within(next, scope),
1298 ));
1299 });
1300 let mut answer = result.expect("hierarchy query callback runs once")?;
1301 answer.edges.sort();
1302 Ok(answer)
1303 }
1304
1305 fn get_polymorphic_matches<T: CodeUnitIndex>(
1306 &self,
1307 target: &CodeUnit,
1308 analyzer: &T,
1309 ) -> HierarchyAnswer
1310 where
1311 Self: Sized,
1312 {
1313 if !target.is_function() {
1314 return HierarchyAnswer::complete(Vec::new());
1315 }
1316
1317 let Some(parent) = analyzer.parent_of(target) else {
1318 return HierarchyAnswer::complete(Vec::new());
1319 };
1320
1321 self.get_descendants(&parent)
1322 }
1323}
1324
1325pub struct DirectDescendantIndex {
1333 nodes: Box<[CodeUnit]>,
1334 row_by_ancestor: HashMap<CodeUnit, u32>,
1335 descendants: CompactRows<u32>,
1336 open_candidates: Box<[CodeUnit]>,
1341}
1342
1343impl DirectDescendantIndex {
1344 pub fn estimated_retained_bytes(&self) -> usize {
1345 let node_bytes = self
1346 .nodes
1347 .iter()
1348 .map(|unit| {
1349 std::mem::size_of::<CodeUnit>()
1350 + unit.fq_name().len()
1351 + unit.signature().map_or(0, str::len)
1352 + unit.source().rel_path().as_os_str().len()
1353 + unit.source().root().as_os_str().len()
1354 })
1355 .sum::<usize>();
1356 std::mem::size_of::<Self>()
1357 + node_bytes * 2
1358 + self.row_by_ancestor.capacity()
1359 * (std::mem::size_of::<CodeUnit>() + std::mem::size_of::<u32>() + 1)
1360 + self.descendants.estimated_bytes() as usize
1361 + self
1362 .open_candidates
1363 .iter()
1364 .map(|unit| std::mem::size_of::<CodeUnit>() + unit.fq_name().len())
1365 .sum::<usize>()
1366 }
1367
1368 pub fn from_indexed_nodes(
1369 nodes: Vec<CodeUnit>,
1370 index_by_node: HashMap<CodeUnit, u32>,
1371 mut edges: Vec<(u32, u32)>,
1372 ) -> Self {
1373 normalize_indexed_edges(&nodes, &index_by_node, &mut edges);
1374
1375 let row_count = usize::from(!edges.is_empty())
1376 + edges
1377 .windows(2)
1378 .filter(|pair| pair[0].0 != pair[1].0)
1379 .count();
1380 let mut row_by_ancestor = HashMap::default();
1381 let mut descendants = CompactRowsBuilder::with_capacity(row_count, edges.len());
1382 let mut cursor = 0;
1383 while cursor < edges.len() {
1384 let ancestor = edges[cursor].0;
1385 let start = cursor;
1386 while cursor < edges.len() && edges[cursor].0 == ancestor {
1387 cursor += 1;
1388 }
1389 let row =
1390 u32::try_from(descendants.rows()).expect("hierarchy index rows must fit in a u32");
1391 row_by_ancestor.insert(nodes[ancestor as usize].clone(), row);
1392 descendants.push_row(
1393 edges[start..cursor]
1394 .iter()
1395 .map(|(_, descendant)| *descendant),
1396 );
1397 }
1398 Self {
1399 nodes: nodes.into_boxed_slice(),
1400 row_by_ancestor,
1401 descendants: descendants.finish(),
1402 open_candidates: Box::default(),
1403 }
1404 }
1405
1406 pub fn with_open_candidates(mut self, mut open_candidates: Vec<CodeUnit>) -> Self {
1408 open_candidates.sort();
1409 open_candidates.dedup();
1410 self.open_candidates = open_candidates.into_boxed_slice();
1411 self
1412 }
1413
1414 pub fn open_candidates(&self) -> &[CodeUnit] {
1416 &self.open_candidates
1417 }
1418
1419 pub fn answer(&self, ancestor: &CodeUnit) -> HierarchyAnswer {
1422 let mut edges: Vec<_> = self.descendants(ancestor).into_iter().collect();
1423 edges.sort();
1424 let mut answer = HierarchyAnswer::complete(edges);
1425 let open_candidates: Vec<_> = self
1426 .open_candidates
1427 .iter()
1428 .filter(|candidate| *candidate != ancestor)
1429 .cloned()
1430 .collect();
1431 if !open_candidates.is_empty() {
1432 answer
1433 .open
1434 .push(HierarchyOpenReason::OpenAncestorCandidates(open_candidates));
1435 }
1436 answer
1437 }
1438
1439 pub fn descendants(&self, ancestor: &CodeUnit) -> HashSet<CodeUnit> {
1440 let Some(row) = self.row_by_ancestor.get(ancestor).copied() else {
1441 return HashSet::default();
1442 };
1443 self.descendants
1444 .row(row as usize)
1445 .iter()
1446 .map(|descendant| self.nodes[*descendant as usize].clone())
1447 .collect()
1448 }
1449}
1450
1451pub fn build_direct_descendant_index<A, P>(
1460 analyzer: &A,
1461 provider: &P,
1462 scope: &DescendantIndexScope<'_>,
1463) -> Option<DirectDescendantIndex>
1464where
1465 A: CodeUnitIndex,
1466 P: TypeHierarchyProvider + ?Sized,
1467{
1468 let mut result = None;
1469 provider.with_hierarchy_query(&mut |query| {
1470 result = Some(build_direct_descendant_index_in_query(
1471 analyzer, query, scope,
1472 ));
1473 });
1474 result.expect("hierarchy query callback runs once")
1475}
1476
1477pub fn build_direct_descendant_index_in_query<A: CodeUnitIndex>(
1479 analyzer: &A,
1480 query: &mut dyn HierarchyQuery,
1481 scope: &DescendantIndexScope<'_>,
1482) -> Option<DirectDescendantIndex> {
1483 let mut candidates = Vec::new();
1484 for candidate in analyzer.all_declarations().filter(CodeUnit::is_class) {
1485 if match scope.admits(&candidate) {
1486 Ok(value) => value,
1487 Err(reason) => {
1488 let _unavailable = reason;
1489 return None;
1490 }
1491 } {
1492 candidates.push(candidate);
1493 }
1494 }
1495 build_direct_descendant_index_from_candidates(
1496 candidates,
1497 |candidate| query.direct_ancestors_within(candidate, scope).ok(),
1498 &scope.keep_going(),
1499 )
1500}
1501
1502pub fn build_direct_descendant_index_from_candidates<F>(
1516 mut candidates: Vec<CodeUnit>,
1517 mut direct_ancestors: F,
1518 keep_going: &dyn Fn() -> bool,
1519) -> Option<DirectDescendantIndex>
1520where
1521 F: FnMut(&CodeUnit) -> Option<HierarchyAnswer>,
1522{
1523 candidates.sort();
1524 candidates.dedup();
1525 let mut types_by_fq_name: HashMap<String, Vec<CodeUnit>> = HashMap::default();
1526 for candidate in &candidates {
1527 types_by_fq_name
1528 .entry(candidate.fq_name())
1529 .or_default()
1530 .push(candidate.clone());
1531 }
1532 let mut nodes = candidates.clone();
1533 let mut index_by_node: HashMap<_, _> = nodes
1534 .iter()
1535 .enumerate()
1536 .map(|(index, node)| {
1537 (
1538 node.clone(),
1539 u32::try_from(index).expect("hierarchy index declarations must fit in a u32"),
1540 )
1541 })
1542 .collect();
1543 let mut edges = Vec::new();
1544 let mut open_candidates = Vec::new();
1545 for candidate in candidates {
1546 if !keep_going() {
1547 return None;
1548 }
1549 let descendant = index_by_node[&candidate];
1550 let answer = direct_ancestors(&candidate)?;
1551 if !answer.keeps_indexed_edges_exact() {
1555 open_candidates.push(candidate.clone());
1556 }
1557 for ancestor in answer.edges {
1558 let ancestor = types_by_fq_name
1559 .get(&ancestor.fq_name())
1560 .and_then(|same_name| {
1561 let mut same_source = same_name
1562 .iter()
1563 .filter(|unit| unit.source() == candidate.source());
1564 let exact = same_source.next()?;
1565 same_source.next().is_none().then(|| exact.clone())
1566 })
1567 .unwrap_or(ancestor);
1568 let ancestor = *index_by_node.entry(ancestor.clone()).or_insert_with(|| {
1569 let index = u32::try_from(nodes.len())
1570 .expect("hierarchy index declarations must fit in a u32");
1571 nodes.push(ancestor);
1572 index
1573 });
1574 edges.push((ancestor, descendant));
1575 }
1576 }
1577 Some(
1578 DirectDescendantIndex::from_indexed_nodes(nodes, index_by_node, edges)
1579 .with_open_candidates(open_candidates),
1580 )
1581}
1582
1583fn traverse_hierarchy(
1584 root: &CodeUnit,
1585 query: &mut dyn HierarchyQuery,
1586 mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> HierarchyAnswer,
1587) -> HierarchyAnswer {
1588 traverse_hierarchy_edges(root, |unit| next(query, unit))
1589}
1590
1591fn traverse_hierarchy_while(
1592 root: &CodeUnit,
1593 query: &mut dyn HierarchyQuery,
1594 cancellation: &CancellationToken,
1595 mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1596) -> Result<HierarchyAnswer, Cancelled> {
1597 traverse_hierarchy_edges_while(root, cancellation, |unit| next(query, unit))
1598}
1599
1600fn traverse_hierarchy_edges_while<F>(
1605 root: &CodeUnit,
1606 cancellation: &CancellationToken,
1607 mut next: F,
1608) -> Result<HierarchyAnswer, Cancelled>
1609where
1610 F: FnMut(&CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1611{
1612 let mut result = HierarchyAnswer::complete(Vec::new());
1613 let mut seen = BTreeSet::new();
1614 let mut queue = VecDeque::from([root.clone()]);
1615 while let Some(current) = queue.pop_front() {
1616 let answer = next(¤t)?;
1617 result.ambiguous.extend(answer.ambiguous);
1618 for reason in answer.open {
1619 if let HierarchyOpenReason::OpenAncestorCandidates(candidates) = &reason
1622 && result.open.iter().any(|seen| {
1623 matches!(seen, HierarchyOpenReason::OpenAncestorCandidates(other) if other == candidates)
1624 })
1625 {
1626 continue;
1627 }
1628 result.open.push(reason);
1629 }
1630 for item in answer.edges {
1631 if seen.insert(item.fq_name()) {
1632 queue.push_back(item.clone());
1633 result.edges.push(item);
1634 }
1635 }
1636 if !queue.is_empty() && cancellation.is_cancelled() {
1637 return Err(Cancelled);
1638 }
1639 }
1640 Ok(result)
1641}
1642
1643fn traverse_hierarchy_edges<F>(root: &CodeUnit, mut next: F) -> HierarchyAnswer
1644where
1645 F: FnMut(&CodeUnit) -> HierarchyAnswer,
1646{
1647 traverse_hierarchy_edges_while(root, &CancellationToken::new(), |unit| Ok(next(unit)))
1650 .expect("unscoped hierarchy traversal cannot stop")
1651}
1652
1653#[cfg(test)]
1654mod hierarchy_traversal_properties {
1655 use super::*;
1656 use crate::analyzer::model::CodeUnitType;
1657 use proptest::prelude::*;
1658 use std::collections::BTreeMap;
1659
1660 const NODES: usize = 8;
1661
1662 fn node(index: usize) -> CodeUnit {
1663 CodeUnit::new(
1664 ProjectFile::new(std::env::temp_dir(), "Hierarchy.java"),
1665 CodeUnitType::Class,
1666 "",
1667 format!("N{index}"),
1668 )
1669 }
1670
1671 #[test]
1672 fn transitive_walks_borrow_one_query_and_preserve_scoped_dispatch() {
1673 use std::sync::atomic::{AtomicUsize, Ordering};
1674 struct Provider(AtomicUsize);
1675 struct Query;
1676 impl HierarchyQuery for Query {
1677 fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1678 let index = index_of(unit);
1679 HierarchyAnswer::complete(if index < 2 {
1680 vec![node(index + 1)]
1681 } else {
1682 Vec::new()
1683 })
1684 }
1685 fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1686 self.direct_ancestors(unit)
1687 }
1688 fn member_family_ancestors(&mut self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1689 MemberFamilyAncestors::default()
1690 }
1691 fn direct_descendants_within(
1692 &mut self,
1693 _unit: &CodeUnit,
1694 _scope: &DescendantIndexScope<'_>,
1695 ) -> Result<HierarchyAnswer, Cancelled> {
1696 Err(Cancelled)
1697 }
1698 }
1699 impl TypeHierarchyProvider for Provider {
1700 fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1701 panic!("the walk must use its query")
1702 }
1703 fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1704 panic!("the walk must use its query")
1705 }
1706 fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1707 self.0.fetch_add(1, Ordering::Relaxed);
1708 run(&mut Query);
1709 }
1710 }
1711 let provider = Provider(AtomicUsize::new(0));
1712 assert_eq!(
1713 provider.get_ancestors(&node(0)).edges,
1714 vec![node(1), node(2)]
1715 );
1716 assert_eq!(provider.0.load(Ordering::Relaxed), 1);
1717 assert_eq!(
1718 provider.get_descendants(&node(0)).edges,
1719 vec![node(1), node(2)]
1720 );
1721 assert_eq!(provider.0.load(Ordering::Relaxed), 2);
1722 let cancellation = CancellationToken::new();
1723 assert!(
1724 provider
1725 .get_descendants_within(
1726 &node(0),
1727 &DescendantIndexScope::whole_workspace(&cancellation)
1728 )
1729 .is_err()
1730 );
1731 assert_eq!(provider.0.load(Ordering::Relaxed), 3);
1732 }
1733
1734 #[test]
1735 fn default_query_forwards_scoped_provider_overrides() {
1736 struct Provider;
1737 impl TypeHierarchyProvider for Provider {
1738 fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1739 HierarchyAnswer::complete(vec![node(1)])
1740 }
1741 fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1742 HierarchyAnswer::complete(vec![node(2)])
1743 }
1744 fn get_direct_ancestors_within(
1745 &self,
1746 _unit: &CodeUnit,
1747 _scope: &DescendantIndexScope<'_>,
1748 ) -> Result<HierarchyAnswer, Cancelled> {
1749 Err(Cancelled)
1750 }
1751 fn member_family_ancestors(&self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1752 MemberFamilyAncestors {
1753 resolved: vec![node(3)],
1754 ..Default::default()
1755 }
1756 }
1757 }
1758 let cancellation = CancellationToken::new();
1759 Provider.with_hierarchy_query(&mut |query| {
1760 assert_eq!(query.direct_ancestors(&node(0)).edges, vec![node(1)]);
1761 assert_eq!(query.direct_descendants(&node(0)).edges, vec![node(2)]);
1762 assert_eq!(
1763 query.member_family_ancestors(&node(0)).resolved,
1764 vec![node(3)]
1765 );
1766 assert!(
1767 query
1768 .direct_ancestors_within(
1769 &node(0),
1770 &DescendantIndexScope::whole_workspace(&cancellation)
1771 )
1772 .is_err()
1773 );
1774 });
1775 }
1776
1777 fn index_of(unit: &CodeUnit) -> usize {
1778 unit.fq_name()[1..].parse().expect("test node name")
1779 }
1780
1781 #[test]
1782 fn closure_preserves_uncertainty_without_traversing_alternatives() {
1783 let mut visited = Vec::new();
1784 let answer = traverse_hierarchy_edges(&node(0), |unit| {
1785 let id = index_of(unit);
1786 visited.push(id);
1787 match id {
1788 0 => HierarchyAnswer {
1789 edges: vec![node(1), node(1)],
1790 ambiguous: vec![vec![node(2), node(3)]],
1791 open: Vec::new(),
1792 },
1793 1 => HierarchyAnswer {
1794 edges: Vec::new(),
1795 ambiguous: vec![vec![node(4), node(5)]],
1796 open: vec![HierarchyOpenReason::UnreadAncestor(
1797 UnreadMemberFamilyAncestor {
1798 name: "External".into(),
1799 inventory: None,
1800 },
1801 )],
1802 },
1803 _ => panic!("ambiguous alternatives must not be traversed"),
1804 }
1805 });
1806 assert_eq!(visited, vec![0, 1]);
1807 assert_eq!(answer.edges, vec![node(1)]);
1808 assert_eq!(
1809 answer.ambiguous,
1810 vec![vec![node(2), node(3)], vec![node(4), node(5)]]
1811 );
1812 assert!(
1813 matches!(answer.open.as_slice(), [HierarchyOpenReason::UnreadAncestor(ancestor)] if ancestor.name == "External")
1814 );
1815 assert!(!answer.is_complete());
1816 }
1817
1818 #[test]
1819 #[brokk_bifrost_test_macros::hardwon(
1820 "#12211: an open candidate tainted its own descendant answer"
1821 )]
1822 #[brokk_bifrost_test_macros::hardwon(
1823 "#12172: an open candidate's own ancestry tainted its descendant query"
1824 )]
1825 fn an_open_candidate_does_not_taint_its_own_descendants() {
1826 let project = ProjectFile::new(std::env::temp_dir(), "Hierarchy.java");
1827 let class = |name: &str| CodeUnit::new(project.clone(), CodeUnitType::Class, "", name);
1828 let base = class("Base");
1829 let open = class("Open");
1830 let derived = class("Derived");
1831 let index = build_direct_descendant_index_from_candidates(
1832 vec![base.clone(), open.clone(), derived.clone()],
1833 |candidate| {
1834 if candidate == &open {
1835 Some(HierarchyAnswer {
1836 edges: vec![base.clone()],
1837 open: vec![HierarchyOpenReason::UnreadAncestor(
1838 UnreadMemberFamilyAncestor {
1839 name: "Mystery".into(),
1840 inventory: None,
1841 },
1842 )],
1843 ambiguous: Vec::new(),
1844 })
1845 } else if candidate == &derived {
1846 Some(HierarchyAnswer::complete(vec![open.clone()]))
1847 } else {
1848 Some(HierarchyAnswer::complete(Vec::new()))
1849 }
1850 },
1851 &|| true,
1852 )
1853 .expect("finished open answers build an index");
1854
1855 let base_answer = index.answer(&base);
1856 assert!(!base_answer.is_complete());
1857 assert!(matches!(
1858 base_answer.open.as_slice(),
1859 [HierarchyOpenReason::OpenAncestorCandidates(candidates)]
1860 if candidates == std::slice::from_ref(&open)
1861 ));
1862
1863 let own = index.answer(&open);
1864 assert!(own.is_complete(), "{own:?}");
1865 assert_eq!(own.edges, vec![derived]);
1866 }
1867
1868 fn graphs() -> impl Strategy<Value = Vec<Vec<usize>>> {
1870 proptest::collection::vec(proptest::collection::vec(0..NODES, 0..5), NODES)
1871 }
1872
1873 fn reference_distances(graph: &[Vec<usize>], root: usize) -> BTreeMap<usize, usize> {
1877 let mut distance: BTreeMap<usize, usize> = BTreeMap::new();
1878 for &next in &graph[root] {
1879 distance.insert(next, 1);
1880 }
1881 loop {
1882 let mut changed = false;
1883 for (from, edges) in graph.iter().enumerate() {
1884 let Some(&base) = distance.get(&from) else {
1885 continue;
1886 };
1887 for &to in edges {
1888 if distance.get(&to).is_none_or(|&known| known > base + 1) {
1889 distance.insert(to, base + 1);
1890 changed = true;
1891 }
1892 }
1893 }
1894 if !changed {
1895 return distance;
1896 }
1897 }
1898 }
1899
1900 proptest! {
1901 #![proptest_config(ProptestConfig::with_cases(128))]
1902
1903 #[test]
1908 fn visits_exactly_the_reachable_set_once_in_breadth_first_order(
1909 graph in graphs(),
1910 root in 0..NODES,
1911 ) {
1912 let mut calls: BTreeMap<usize, usize> = BTreeMap::new();
1913 let result = traverse_hierarchy_edges(&node(root), |unit| {
1914 let id = index_of(unit);
1915 *calls.entry(id).or_default() += 1;
1916 HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())
1917 });
1918 let found: Vec<usize> = result.edges.iter().map(index_of).collect();
1919
1920 let distance = reference_distances(&graph, root);
1921 let unique: BTreeSet<usize> = found.iter().copied().collect();
1922 prop_assert_eq!(found.len(), unique.len(), "a declaration was returned twice: {:?}", found);
1923 prop_assert_eq!(unique, distance.keys().copied().collect::<BTreeSet<_>>());
1924 prop_assert!(
1925 found.windows(2).all(|pair| distance[&pair[0]] <= distance[&pair[1]]),
1926 "not breadth-first: {:?} with distances {:?}", found, distance
1927 );
1928 prop_assert!(
1931 calls.iter().all(|(&id, &count)| count == 1 || (id == root && count == 2)),
1932 "repeated expansion: {:?}", calls
1933 );
1934
1935 let live = CancellationToken::new();
1937 let guarded = traverse_hierarchy_edges_while(&node(root), &live, |unit| {
1938 Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1939 });
1940 let guarded = guarded.expect("live traversal");
1941 prop_assert!(guarded.is_complete());
1942 prop_assert_eq!(guarded.edges, result.edges);
1943 }
1944
1945 #[test]
1949 fn guarded_traversal_never_returns_a_partial_answer(
1950 graph in graphs(),
1951 root in 0..NODES,
1952 fail_on in 0..NODES,
1953 ) {
1954 let reachable = reference_distances(&graph, root);
1955 let failing = traverse_hierarchy_edges_while(&node(root), &CancellationToken::new(), |unit| {
1956 let id = index_of(unit);
1957 if id == fail_on { Err(Cancelled) } else { Ok(HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())) }
1958 });
1959 let requested = fail_on == root || reachable.contains_key(&fail_on);
1962 prop_assert_eq!(failing.is_err(), requested);
1963
1964 let cancelled = CancellationToken::new();
1965 cancelled.cancel();
1966 let stopped = traverse_hierarchy_edges_while(&node(root), &cancelled, |unit| {
1967 Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1968 });
1969 prop_assert_eq!(stopped.is_err(), !graph[root].is_empty());
1970 if graph[root].is_empty() {
1971 let stopped = stopped.expect("empty traversal");
1972 prop_assert!(stopped.is_complete());
1973 prop_assert!(stopped.edges.is_empty());
1974 }
1975 }
1976 }
1977}