1use crate::analyzer::code_unit_index::CodeUnitIndex;
2use crate::analyzer::model::{CodeUnit, ImportInfo, ProjectFile};
3use crate::analyzer::pool_memo::{KeyedPoolSafeMemo, 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 dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>,
42 pub complete: bool,
43}
44
45#[derive(Debug, Clone, PartialEq, Eq, Hash)]
50pub struct ImportLookupDependency {
51 pub import_ordinal: u32,
52 pub consulted_file: ProjectFile,
53 pub name: String,
54}
55
56#[derive(Debug, Clone, Default, PartialEq, Eq)]
60pub struct ImportResolutionDependencies {
61 pub lookups: Vec<ImportLookupDependency>,
62 pub missing_module_path_keys: Vec<(u32, String)>,
63}
64
65#[derive(Debug, Clone, PartialEq, Eq, Hash)]
71pub struct ImportGraphBindingSurface {
72 pub module_path: String,
73 pub name: String,
74 pub namespace: String,
75 pub visibility_kind: String,
76 pub visibility_scope: String,
77 pub origin_file: ProjectFile,
78 pub origin_module_path: String,
79 pub origin_name: String,
80 pub route_files: Vec<ProjectFile>,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq)]
86pub struct ImportGraphInputDigests {
87 pub binding_surface: [u8; 32],
88 pub import_rows: [u8; 32],
89}
90
91pub type ImportedFileEdgeTargets = HashMap<ProjectFile, Vec<Value>>;
93
94#[derive(Debug, Clone, PartialEq, Eq)]
98pub struct ImportedFileEdgeFacts {
99 pub import_ordinal: u32,
100 pub edges: ImportedFileEdgeTargets,
101}
102
103impl AdditionalFileDependencies {
104 pub fn complete(dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>) -> Self {
105 Self {
106 dependencies,
107 complete: true,
108 }
109 }
110
111 pub fn incomplete(dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>) -> Self {
112 Self {
113 dependencies,
114 complete: false,
115 }
116 }
117}
118
119impl<T: Any> CapabilityProvider for T {
120 fn as_any(&self) -> &dyn Any {
121 self
122 }
123}
124
125pub trait ImportAnalysisProvider: Send + Sync {
126 fn imported_code_units_of(&self, file: &ProjectFile) -> Arc<HashSet<CodeUnit>>;
132 fn referencing_files_of(&self, file: &ProjectFile) -> HashSet<ProjectFile>;
133
134 fn referencing_files_of_targets(
142 &self,
143 targets: &HashSet<ProjectFile>,
144 cancellation: &CancellationToken,
145 ) -> HashSet<ProjectFile> {
146 let mut referencing = HashSet::default();
147 for target in targets {
148 if cancellation.is_cancelled() {
149 break;
150 }
151 referencing.extend(self.referencing_files_of(target));
152 }
153 referencing
154 }
155
156 fn import_infos_for_files(
160 &self,
161 _files: &[ProjectFile],
162 ) -> Option<HashMap<ProjectFile, Vec<ImportInfo>>> {
163 None
164 }
165
166 fn file_dependency_facts_for_files(
173 &self,
174 files: &[ProjectFile],
175 ) -> Option<HashMap<ProjectFile, FileDependencyFacts>> {
176 self.import_infos_for_files(files).map(|infos| {
177 infos
178 .into_iter()
179 .map(|(file, imports)| {
180 (
181 file,
182 FileDependencyFacts {
183 imports,
184 contains_tests: None,
185 },
186 )
187 })
188 .collect()
189 })
190 }
191
192 fn has_complete_import_resolution_dependencies(&self) -> bool {
195 false
196 }
197
198 fn import_graph_module_path_keys_for_files(
202 &self,
203 _files: &[ProjectFile],
204 ) -> Option<HashMap<ProjectFile, Vec<String>>> {
205 None
206 }
207
208 fn import_graph_binding_surfaces_for_files(
212 &self,
213 _files: &[ProjectFile],
214 _cancellation: Option<&CancellationToken>,
215 ) -> Option<HashMap<ProjectFile, Vec<ImportGraphBindingSurface>>> {
216 None
217 }
218
219 fn import_graph_input_digests_for_files(
223 &self,
224 _files: &[ProjectFile],
225 _cancellation: Option<&CancellationToken>,
226 ) -> Option<HashMap<ProjectFile, ImportGraphInputDigests>> {
227 None
228 }
229
230 fn import_resolution_dependencies_for_files(
235 &self,
236 _files: &[ProjectFile],
237 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
238 _cancellation: Option<&CancellationToken>,
239 ) -> Option<HashMap<ProjectFile, ImportResolutionDependencies>> {
240 None
241 }
242
243 fn for_each_import_edge_facts_from_infos(
250 &self,
251 files: &[ProjectFile],
252 import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
253 selected_ordinals: &HashMap<ProjectFile, Vec<u32>>,
254 cancellation: Option<&CancellationToken>,
255 visit: &mut dyn FnMut(&ProjectFile, Vec<ImportedFileEdgeFacts>) -> bool,
256 ) -> Option<()> {
257 if !selected_ordinals.is_empty() {
258 return None;
259 }
260 self.for_each_imported_file_edges_from_infos(
261 files,
262 import_infos,
263 cancellation,
264 &mut |file, edges| {
265 visit(
266 file,
267 vec![ImportedFileEdgeFacts {
268 import_ordinal: u32::MAX,
269 edges,
270 }],
271 )
272 },
273 )
274 }
275
276 fn import_resolution_dependencies_for_ordinals(
280 &self,
281 files: &[ProjectFile],
282 import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
283 selected_ordinals: &HashMap<ProjectFile, Vec<u32>>,
284 cancellation: Option<&CancellationToken>,
285 ) -> Option<HashMap<ProjectFile, ImportResolutionDependencies>> {
286 if !selected_ordinals.is_empty() {
287 return None;
288 }
289 self.import_resolution_dependencies_for_files(files, import_infos, cancellation)
290 }
291
292 fn additional_direct_file_dependencies(
301 &self,
302 _files: &[ProjectFile],
303 _cancellation: &CancellationToken,
304 ) -> Option<AdditionalFileDependencies> {
305 Some(AdditionalFileDependencies::complete(HashMap::default()))
306 }
307
308 fn import_info_of(&self, _token: QueryToken<'_>, _file: &ProjectFile) -> Vec<ImportInfo> {
313 Vec::new()
314 }
315
316 fn import_info_of_checked(
324 &self,
325 _token: QueryToken<'_>,
326 _file: &ProjectFile,
327 ) -> Option<Vec<ImportInfo>> {
328 None
329 }
330
331 fn imported_code_units_from_infos(
334 &self,
335 _file: &ProjectFile,
336 _imports: &[ImportInfo],
337 ) -> Option<Arc<HashSet<CodeUnit>>> {
338 None
339 }
340
341 fn imported_files_from_infos(
345 &self,
346 _file: &ProjectFile,
347 _imports: &[ImportInfo],
348 ) -> Option<HashSet<ProjectFile>> {
349 None
350 }
351
352 fn imported_file_edge_provenance_from_infos(
357 &self,
358 _file: &ProjectFile,
359 _imports: &[ImportInfo],
360 ) -> Option<ImportedFileEdgeTargets> {
361 None
362 }
363
364 fn for_each_imported_files_from_infos(
370 &self,
371 _files: &[ProjectFile],
372 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
373 _cancellation: Option<&CancellationToken>,
374 _visit: &mut dyn FnMut(&ProjectFile, HashSet<ProjectFile>) -> bool,
375 ) -> Option<()> {
376 None
377 }
378
379 fn for_each_imported_file_edges_from_infos(
383 &self,
384 files: &[ProjectFile],
385 import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
386 cancellation: Option<&CancellationToken>,
387 visit: &mut dyn FnMut(&ProjectFile, ImportedFileEdgeTargets) -> bool,
388 ) -> Option<()> {
389 let mut visit_targets = |file: &ProjectFile, targets: HashSet<ProjectFile>| {
390 let facts = import_infos.and_then(|infos| infos.get(file)).map_or_else(
391 || serde_json::json!({ "kind": "provider_resolved_import_edge" }),
392 |imports| {
393 serde_json::json!({
394 "kind": "structured_import_facts",
395 "facts": imports
396 })
397 },
398 );
399 let edges = targets
400 .into_iter()
401 .map(|target| (target, vec![facts.clone()]))
402 .collect();
403 visit(file, edges)
404 };
405 self.for_each_imported_files_from_infos(
406 files,
407 import_infos,
408 cancellation,
409 &mut visit_targets,
410 )
411 }
412
413 fn relevant_imports_for(&self, _code_unit: &CodeUnit) -> HashSet<String> {
414 HashSet::default()
415 }
416
417 fn could_import_file(
423 &self,
424 _source_file: &ProjectFile,
425 _imports: &[ImportInfo],
426 _target: &ProjectFile,
427 ) -> bool {
428 false
429 }
430
431 fn prefetch_import_targets(
448 &self,
449 _files: &[ProjectFile],
450 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
451 _cancellation: &crate::cancellation::CancellationToken,
452 ) {
453 }
454
455 fn prefetch_file_dependency_targets(
463 &self,
464 _files: &[ProjectFile],
465 _import_infos: Option<&HashMap<ProjectFile, Vec<ImportInfo>>>,
466 _cancellation: &crate::cancellation::CancellationToken,
467 ) {
468 }
469
470 fn import_reachability(
483 &self,
484 source_file: &ProjectFile,
485 imports: &[ImportInfo],
486 target: &ProjectFile,
487 ) -> ImportReachability {
488 if self.could_import_file(source_file, imports, target) {
489 ImportReachability::Reaches
490 } else {
491 ImportReachability::Unknown
492 }
493 }
494}
495
496#[derive(Debug, Clone, Copy, PartialEq, Eq)]
511pub enum ImportReachability {
512 Reaches,
514 DoesNotReach,
516 Unknown,
519}
520
521pub fn resolve_imported_files_from_infos(
526 provider: &dyn ImportAnalysisProvider,
527 file: &ProjectFile,
528 imports: &[ImportInfo],
529) -> HashSet<ProjectFile> {
530 provider
531 .imported_files_from_infos(file, imports)
532 .unwrap_or_else(|| {
533 provider
534 .imported_code_units_from_infos(file, imports)
535 .unwrap_or_else(|| provider.imported_code_units_of(file))
536 .iter()
537 .map(|unit| unit.source().clone())
538 .collect()
539 })
540}
541
542pub fn build_reverse_import_index<F>(
543 files: &[ProjectFile],
544 resolve_imported: F,
545 parallel: bool,
546) -> HashMap<ProjectFile, Arc<HashSet<ProjectFile>>>
547where
548 F: Fn(&ProjectFile) -> Arc<HashSet<CodeUnit>> + Sync,
549{
550 build_reverse_file_index(
551 files,
552 |file| imported_source_files(&resolve_imported(file)),
553 parallel,
554 )
555}
556
557fn imported_source_files(imported: &HashSet<CodeUnit>) -> Vec<ProjectFile> {
558 imported
559 .iter()
560 .map(|code_unit| code_unit.source().clone())
561 .collect()
562}
563
564pub type ReverseFileIndex = HashMap<ProjectFile, Arc<HashSet<ProjectFile>>>;
565
566pub fn memoized_reverse_import_index<F, Files>(
567 memo: &PoolSafeMemo<ReverseFileIndex>,
568 files: Files,
569 resolve_imported: F,
570) -> Arc<ReverseFileIndex>
571where
572 F: Fn(&ProjectFile) -> Arc<HashSet<CodeUnit>> + Sync + Copy,
573 Files: Fn() -> Vec<ProjectFile> + Copy,
574{
575 memoized_reverse_file_index(memo, files, |file| {
576 imported_source_files(&resolve_imported(file))
577 })
578}
579
580pub fn memoized_reverse_file_index<F, I, Files>(
581 memo: &PoolSafeMemo<ReverseFileIndex>,
582 files: Files,
583 resolve_targets: F,
584) -> Arc<ReverseFileIndex>
585where
586 F: Fn(&ProjectFile) -> I + Sync + Copy,
587 I: IntoIterator<Item = ProjectFile>,
588 Files: Fn() -> Vec<ProjectFile> + Copy,
589{
590 memo.get_or_build(
591 || {
592 let files = files();
593 build_reverse_file_index(&files, resolve_targets, true)
594 },
595 || {
596 let files = files();
597 build_reverse_file_index(&files, resolve_targets, false)
598 },
599 )
600}
601
602pub fn build_reverse_file_index<F, I>(
603 files: &[ProjectFile],
604 resolve_targets: F,
605 parallel: bool,
606) -> HashMap<ProjectFile, Arc<HashSet<ProjectFile>>>
607where
608 F: Fn(&ProjectFile) -> I + Sync,
609 I: IntoIterator<Item = ProjectFile>,
610{
611 let context = super::carried_context::CarriedContext::current();
612 let collect_edges = |file: &ProjectFile| {
613 context.run(|| {
614 let source = file.clone();
615 resolve_targets(file)
616 .into_iter()
617 .filter_map(move |target| (target != source).then(|| (target, source.clone())))
618 .collect::<Vec<_>>()
619 })
620 };
621 let edges: Vec<_> = if parallel {
622 files.par_iter().flat_map(collect_edges).collect()
623 } else {
624 files.iter().flat_map(collect_edges).collect()
625 };
626
627 let mut reverse: HashMap<ProjectFile, HashSet<ProjectFile>> = HashMap::default();
628 for (target, source) in edges {
629 reverse.entry(target).or_default().insert(source);
630 }
631 reverse
632 .into_iter()
633 .map(|(file, refs)| (file, Arc::new(refs)))
634 .collect()
635}
636
637pub trait TypeAliasProvider: CapabilityProvider + Send + Sync {
641 fn is_type_alias(&self, _code_unit: &CodeUnit) -> bool {
642 false
643 }
644}
645
646pub fn provider_declares_type_alias(
648 provider: Option<&dyn TypeAliasProvider>,
649 code_unit: &CodeUnit,
650) -> bool {
651 provider.is_some_and(|provider| provider.is_type_alias(code_unit))
652}
653
654pub trait TestDetectionProvider: CapabilityProvider {}
655
656#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
662pub enum DescendantIndexVariant {
663 WholeWorkspace,
665 ProductionOnly,
669}
670
671#[derive(Clone, Copy)]
688pub struct DescendantIndexScope<'a> {
689 cancellation: &'a CancellationToken,
690 excluded_source: Option<&'a dyn Fn(&ProjectFile) -> bool>,
691}
692
693impl<'a> DescendantIndexScope<'a> {
694 pub fn whole_workspace(cancellation: &'a CancellationToken) -> Self {
696 Self {
697 cancellation,
698 excluded_source: None,
699 }
700 }
701
702 pub fn excluding_sources(
706 cancellation: &'a CancellationToken,
707 excluded: &'a dyn Fn(&ProjectFile) -> bool,
708 ) -> Self {
709 Self {
710 cancellation,
711 excluded_source: Some(excluded),
712 }
713 }
714
715 pub fn cancellation(&self) -> &'a CancellationToken {
716 self.cancellation
717 }
718
719 pub fn variant(&self) -> DescendantIndexVariant {
720 match self.excluded_source {
721 Some(_) => DescendantIndexVariant::ProductionOnly,
722 None => DescendantIndexVariant::WholeWorkspace,
723 }
724 }
725
726 pub fn keep_going(&self) -> impl Fn() -> bool + use<'_> {
729 || !self.cancellation.is_cancelled()
730 }
731
732 pub fn admits(&self, declaration: &CodeUnit) -> bool {
734 self.excluded_source
735 .is_none_or(|excluded| !excluded(declaration.source()))
736 }
737}
738
739#[derive(Debug, Clone, Copy, PartialEq, Eq)]
741pub struct Cancelled;
742
743fn query_within_scope<T>(
744 scope: &DescendantIndexScope<'_>,
745 query: impl FnOnce() -> T,
746) -> Result<T, Cancelled> {
747 if scope.cancellation().is_cancelled() {
748 Err(Cancelled)
749 } else {
750 Ok(query())
751 }
752}
753
754#[derive(Debug, Clone, Copy)]
756pub struct PlatformInventoryMethod {
757 pub name: &'static str,
758 pub parameters: &'static [&'static str],
759 pub returns: &'static str,
760}
761
762#[derive(Debug, Clone)]
764pub struct UnreadMemberFamilyAncestor {
765 pub name: String,
766 pub inventory: Option<&'static [PlatformInventoryMethod]>,
767}
768
769#[derive(Debug, Default)]
770pub struct MemberFamilyAncestors {
771 pub resolved: Vec<CodeUnit>,
772 pub unread: Vec<UnreadMemberFamilyAncestor>,
773}
774
775#[derive(Debug, Clone)]
777pub enum HierarchyOpenReason {
778 MemberFamily(crate::analyzer::structural::resolution::MemberFamilyReason),
781 DescendantIndexUnavailable,
783 UnreadAncestor(UnreadMemberFamilyAncestor),
785}
786
787#[derive(Debug, Default)]
793pub struct HierarchyAnswer {
794 pub edges: Vec<CodeUnit>,
795 pub ambiguous: Vec<Vec<CodeUnit>>,
796 pub open: Vec<HierarchyOpenReason>,
797}
798
799impl HierarchyAnswer {
800 pub fn complete(edges: Vec<CodeUnit>) -> Self {
802 Self {
803 edges,
804 ambiguous: Vec::new(),
805 open: Vec::new(),
806 }
807 }
808
809 pub fn merge(&mut self, other: Self) {
811 self.edges.extend(other.edges);
812 self.edges.sort();
813 self.edges.dedup();
814 self.ambiguous.extend(other.ambiguous);
815 self.open.extend(other.open);
816 }
817
818 pub fn is_complete(&self) -> bool {
819 self.ambiguous.is_empty() && self.open.is_empty()
820 }
821
822 pub fn definite(&self) -> &[CodeUnit] {
825 &self.edges
826 }
827}
828
829pub trait TypeHierarchyProvider: Send + Sync {
830 fn get_direct_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
831 fn get_direct_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
832
833 fn member_family_ancestors(&self, owner: &CodeUnit) -> MemberFamilyAncestors {
836 MemberFamilyAncestors {
837 resolved: self.get_direct_ancestors(owner).edges,
838 unread: Vec::new(),
839 }
840 }
841
842 fn member_family_inventory_matches(
845 &self,
846 _member: &CodeUnit,
847 _inventory: &[PlatformInventoryMethod],
848 ) -> bool {
849 true
850 }
851
852 fn supports_type_hierarchy(&self, code_unit: &CodeUnit) -> bool {
853 code_unit.is_class()
854 }
855
856 fn get_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
857 traverse_hierarchy(code_unit, |next| self.get_direct_ancestors(next))
858 }
859
860 fn get_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
861 let mut answer = traverse_hierarchy(code_unit, |next| self.get_direct_descendants(next));
862 answer.edges.sort();
863 answer
864 }
865
866 fn get_direct_ancestors_within(
875 &self,
876 code_unit: &CodeUnit,
877 scope: &DescendantIndexScope<'_>,
878 ) -> Result<HierarchyAnswer, Cancelled> {
879 query_within_scope(scope, || self.get_direct_ancestors(code_unit))
880 }
881
882 fn get_direct_descendants_within(
901 &self,
902 code_unit: &CodeUnit,
903 scope: &DescendantIndexScope<'_>,
904 ) -> Result<HierarchyAnswer, Cancelled> {
905 query_within_scope(scope, || self.get_direct_descendants(code_unit))
906 }
907
908 fn get_descendants_within(
912 &self,
913 code_unit: &CodeUnit,
914 scope: &DescendantIndexScope<'_>,
915 ) -> Result<HierarchyAnswer, Cancelled> {
916 let mut answer = traverse_hierarchy_while(code_unit, scope.cancellation(), |next| {
917 self.get_direct_descendants_within(next, scope)
918 })?;
919 answer.edges.sort();
920 Ok(answer)
921 }
922
923 fn get_polymorphic_matches<T: CodeUnitIndex>(
924 &self,
925 target: &CodeUnit,
926 analyzer: &T,
927 ) -> HierarchyAnswer
928 where
929 Self: Sized,
930 {
931 if !target.is_function() {
932 return HierarchyAnswer::complete(Vec::new());
933 }
934
935 let Some(parent) = analyzer.parent_of(target) else {
936 return HierarchyAnswer::complete(Vec::new());
937 };
938
939 self.get_descendants(&parent)
940 }
941}
942
943pub struct DirectDescendantIndex {
945 nodes: Box<[CodeUnit]>,
946 row_by_ancestor: HashMap<CodeUnit, u32>,
947 descendants: CompactRows<u32>,
948}
949
950impl DirectDescendantIndex {
951 pub fn from_indexed_nodes(
952 nodes: Vec<CodeUnit>,
953 index_by_node: HashMap<CodeUnit, u32>,
954 mut edges: Vec<(u32, u32)>,
955 ) -> Self {
956 normalize_indexed_edges(&nodes, &index_by_node, &mut edges);
957
958 let row_count = usize::from(!edges.is_empty())
959 + edges
960 .windows(2)
961 .filter(|pair| pair[0].0 != pair[1].0)
962 .count();
963 let mut row_by_ancestor = HashMap::default();
964 let mut descendants = CompactRowsBuilder::with_capacity(row_count, edges.len());
965 let mut cursor = 0;
966 while cursor < edges.len() {
967 let ancestor = edges[cursor].0;
968 let start = cursor;
969 while cursor < edges.len() && edges[cursor].0 == ancestor {
970 cursor += 1;
971 }
972 let row =
973 u32::try_from(descendants.rows()).expect("hierarchy index rows must fit in a u32");
974 row_by_ancestor.insert(nodes[ancestor as usize].clone(), row);
975 descendants.push_row(
976 edges[start..cursor]
977 .iter()
978 .map(|(_, descendant)| *descendant),
979 );
980 }
981 Self {
982 nodes: nodes.into_boxed_slice(),
983 row_by_ancestor,
984 descendants: descendants.finish(),
985 }
986 }
987
988 pub fn descendants(&self, ancestor: &CodeUnit) -> HashSet<CodeUnit> {
989 let Some(row) = self.row_by_ancestor.get(ancestor).copied() else {
990 return HashSet::default();
991 };
992 self.descendants
993 .row(row as usize)
994 .iter()
995 .map(|descendant| self.nodes[*descendant as usize].clone())
996 .collect()
997 }
998}
999
1000pub fn descendants_from_variant_index(
1009 index: &KeyedPoolSafeMemo<DescendantIndexVariant, DirectDescendantIndex>,
1010 scope: &DescendantIndexScope<'_>,
1011 code_unit: &CodeUnit,
1012 build: impl Fn() -> Option<DirectDescendantIndex>,
1013) -> Option<HashSet<CodeUnit>> {
1014 Some(
1015 index
1016 .cell(&scope.variant())
1017 .get_or_build_while(&scope.keep_going(), &build, &build)?
1020 .descendants(code_unit),
1021 )
1022}
1023
1024pub fn build_direct_descendant_index<A, P>(
1032 analyzer: &A,
1033 provider: &P,
1034 scope: &DescendantIndexScope<'_>,
1035) -> Option<DirectDescendantIndex>
1036where
1037 A: CodeUnitIndex,
1038 P: TypeHierarchyProvider + ?Sized,
1039{
1040 build_direct_descendant_index_from_candidates(
1041 analyzer
1042 .all_declarations()
1043 .filter(|candidate| candidate.is_class() && scope.admits(candidate))
1044 .collect(),
1045 |candidate| {
1046 let answer = provider
1047 .get_direct_ancestors_within(candidate, scope)
1048 .ok()?;
1049 answer.is_complete().then_some(answer.edges)
1052 },
1053 &scope.keep_going(),
1054 )
1055}
1056
1057pub fn build_direct_descendant_index_from_candidates<F>(
1067 mut candidates: Vec<CodeUnit>,
1068 mut direct_ancestors: F,
1069 keep_going: &dyn Fn() -> bool,
1070) -> Option<DirectDescendantIndex>
1071where
1072 F: FnMut(&CodeUnit) -> Option<Vec<CodeUnit>>,
1073{
1074 candidates.sort();
1075 candidates.dedup();
1076 let mut types_by_fq_name: HashMap<String, Vec<CodeUnit>> = HashMap::default();
1077 for candidate in &candidates {
1078 types_by_fq_name
1079 .entry(candidate.fq_name())
1080 .or_default()
1081 .push(candidate.clone());
1082 }
1083 let mut nodes = candidates.clone();
1084 let mut index_by_node: HashMap<_, _> = nodes
1085 .iter()
1086 .enumerate()
1087 .map(|(index, node)| {
1088 (
1089 node.clone(),
1090 u32::try_from(index).expect("hierarchy index declarations must fit in a u32"),
1091 )
1092 })
1093 .collect();
1094 let mut edges = Vec::new();
1095 for candidate in candidates {
1096 if !keep_going() {
1097 return None;
1098 }
1099 let descendant = index_by_node[&candidate];
1100 for ancestor in direct_ancestors(&candidate)? {
1101 let ancestor = types_by_fq_name
1102 .get(&ancestor.fq_name())
1103 .and_then(|same_name| {
1104 let mut same_source = same_name
1105 .iter()
1106 .filter(|unit| unit.source() == candidate.source());
1107 let exact = same_source.next()?;
1108 same_source.next().is_none().then(|| exact.clone())
1109 })
1110 .unwrap_or(ancestor);
1111 let ancestor = *index_by_node.entry(ancestor.clone()).or_insert_with(|| {
1112 let index = u32::try_from(nodes.len())
1113 .expect("hierarchy index declarations must fit in a u32");
1114 nodes.push(ancestor);
1115 index
1116 });
1117 edges.push((ancestor, descendant));
1118 }
1119 }
1120 Some(DirectDescendantIndex::from_indexed_nodes(
1121 nodes,
1122 index_by_node,
1123 edges,
1124 ))
1125}
1126
1127fn traverse_hierarchy_while<F>(
1132 root: &CodeUnit,
1133 cancellation: &CancellationToken,
1134 mut next: F,
1135) -> Result<HierarchyAnswer, Cancelled>
1136where
1137 F: FnMut(&CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1138{
1139 let mut result = HierarchyAnswer::default();
1140 let mut seen = BTreeSet::new();
1141 let mut queue = VecDeque::from([root.clone()]);
1142 while let Some(current) = queue.pop_front() {
1143 let answer = next(¤t)?;
1144 result.ambiguous.extend(answer.ambiguous);
1145 result.open.extend(answer.open);
1146 for item in answer.edges {
1147 if seen.insert(item.fq_name()) {
1148 queue.push_back(item.clone());
1149 result.edges.push(item);
1150 }
1151 }
1152 if !queue.is_empty() && cancellation.is_cancelled() {
1153 return Err(Cancelled);
1154 }
1155 }
1156 Ok(result)
1157}
1158
1159fn traverse_hierarchy<F>(root: &CodeUnit, mut next: F) -> HierarchyAnswer
1160where
1161 F: FnMut(&CodeUnit) -> HierarchyAnswer,
1162{
1163 traverse_hierarchy_while(root, &CancellationToken::new(), |unit| Ok(next(unit)))
1166 .expect("unscoped hierarchy traversal cannot stop")
1167}
1168
1169#[cfg(test)]
1170mod hierarchy_traversal_properties {
1171 use super::*;
1172 use crate::analyzer::model::CodeUnitType;
1173 use proptest::prelude::*;
1174 use std::collections::BTreeMap;
1175
1176 const NODES: usize = 8;
1177
1178 fn node(index: usize) -> CodeUnit {
1179 CodeUnit::new(
1180 ProjectFile::new(std::env::temp_dir(), "Hierarchy.java"),
1181 CodeUnitType::Class,
1182 "",
1183 format!("N{index}"),
1184 )
1185 }
1186
1187 fn index_of(unit: &CodeUnit) -> usize {
1188 unit.fq_name()[1..].parse().expect("test node name")
1189 }
1190
1191 #[test]
1192 fn closure_preserves_uncertainty_without_traversing_alternatives() {
1193 let mut visited = Vec::new();
1194 let answer = traverse_hierarchy(&node(0), |unit| {
1195 let id = index_of(unit);
1196 visited.push(id);
1197 match id {
1198 0 => HierarchyAnswer {
1199 edges: vec![node(1), node(1)],
1200 ambiguous: vec![vec![node(2), node(3)]],
1201 open: Vec::new(),
1202 },
1203 1 => HierarchyAnswer {
1204 edges: Vec::new(),
1205 ambiguous: vec![vec![node(4), node(5)]],
1206 open: vec![HierarchyOpenReason::UnreadAncestor(
1207 UnreadMemberFamilyAncestor {
1208 name: "External".into(),
1209 inventory: None,
1210 },
1211 )],
1212 },
1213 _ => panic!("ambiguous alternatives must not be traversed"),
1214 }
1215 });
1216 assert_eq!(visited, vec![0, 1]);
1217 assert_eq!(answer.edges, vec![node(1)]);
1218 assert_eq!(
1219 answer.ambiguous,
1220 vec![vec![node(2), node(3)], vec![node(4), node(5)]]
1221 );
1222 assert!(
1223 matches!(answer.open.as_slice(), [HierarchyOpenReason::UnreadAncestor(ancestor)] if ancestor.name == "External")
1224 );
1225 assert!(!answer.is_complete());
1226 }
1227
1228 fn graphs() -> impl Strategy<Value = Vec<Vec<usize>>> {
1230 proptest::collection::vec(proptest::collection::vec(0..NODES, 0..5), NODES)
1231 }
1232
1233 fn reference_distances(graph: &[Vec<usize>], root: usize) -> BTreeMap<usize, usize> {
1237 let mut distance: BTreeMap<usize, usize> = BTreeMap::new();
1238 for &next in &graph[root] {
1239 distance.insert(next, 1);
1240 }
1241 loop {
1242 let mut changed = false;
1243 for (from, edges) in graph.iter().enumerate() {
1244 let Some(&base) = distance.get(&from) else {
1245 continue;
1246 };
1247 for &to in edges {
1248 if distance.get(&to).is_none_or(|&known| known > base + 1) {
1249 distance.insert(to, base + 1);
1250 changed = true;
1251 }
1252 }
1253 }
1254 if !changed {
1255 return distance;
1256 }
1257 }
1258 }
1259
1260 proptest! {
1261 #![proptest_config(ProptestConfig::with_cases(128))]
1262
1263 #[test]
1268 fn visits_exactly_the_reachable_set_once_in_breadth_first_order(
1269 graph in graphs(),
1270 root in 0..NODES,
1271 ) {
1272 let mut calls: BTreeMap<usize, usize> = BTreeMap::new();
1273 let result = traverse_hierarchy(&node(root), |unit| {
1274 let id = index_of(unit);
1275 *calls.entry(id).or_default() += 1;
1276 HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())
1277 });
1278 let found: Vec<usize> = result.edges.iter().map(index_of).collect();
1279
1280 let distance = reference_distances(&graph, root);
1281 let unique: BTreeSet<usize> = found.iter().copied().collect();
1282 prop_assert_eq!(found.len(), unique.len(), "a declaration was returned twice: {:?}", found);
1283 prop_assert_eq!(unique, distance.keys().copied().collect::<BTreeSet<_>>());
1284 prop_assert!(
1285 found.windows(2).all(|pair| distance[&pair[0]] <= distance[&pair[1]]),
1286 "not breadth-first: {:?} with distances {:?}", found, distance
1287 );
1288 prop_assert!(
1291 calls.iter().all(|(&id, &count)| count == 1 || (id == root && count == 2)),
1292 "repeated expansion: {:?}", calls
1293 );
1294
1295 let live = CancellationToken::new();
1297 let guarded = traverse_hierarchy_while(&node(root), &live, |unit| {
1298 Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1299 });
1300 let guarded = guarded.expect("live traversal");
1301 prop_assert!(guarded.is_complete());
1302 prop_assert_eq!(guarded.edges, result.edges);
1303 }
1304
1305 #[test]
1309 fn guarded_traversal_never_returns_a_partial_answer(
1310 graph in graphs(),
1311 root in 0..NODES,
1312 fail_on in 0..NODES,
1313 ) {
1314 let reachable = reference_distances(&graph, root);
1315 let failing = traverse_hierarchy_while(&node(root), &CancellationToken::new(), |unit| {
1316 let id = index_of(unit);
1317 if id == fail_on { Err(Cancelled) } else { Ok(HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())) }
1318 });
1319 let requested = fail_on == root || reachable.contains_key(&fail_on);
1322 prop_assert_eq!(failing.is_err(), requested);
1323
1324 let cancelled = CancellationToken::new();
1325 cancelled.cancel();
1326 let stopped = traverse_hierarchy_while(&node(root), &cancelled, |unit| {
1327 Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1328 });
1329 prop_assert_eq!(stopped.is_err(), !graph[root].is_empty());
1330 if graph[root].is_empty() {
1331 let stopped = stopped.expect("empty traversal");
1332 prop_assert!(stopped.is_complete());
1333 prop_assert!(stopped.edges.is_empty());
1334 }
1335 }
1336 }
1337}