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: CapabilityProvider + 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 collect_edges = |file: &ProjectFile| {
612 let source = file.clone();
613 resolve_targets(file)
614 .into_iter()
615 .filter_map(move |target| (target != source).then(|| (target, source.clone())))
616 .collect::<Vec<_>>()
617 };
618 let edges: Vec<_> = if parallel {
619 files.par_iter().flat_map(collect_edges).collect()
620 } else {
621 files.iter().flat_map(collect_edges).collect()
622 };
623
624 let mut reverse: HashMap<ProjectFile, HashSet<ProjectFile>> = HashMap::default();
625 for (target, source) in edges {
626 reverse.entry(target).or_default().insert(source);
627 }
628 reverse
629 .into_iter()
630 .map(|(file, refs)| (file, Arc::new(refs)))
631 .collect()
632}
633
634pub trait TypeAliasProvider: CapabilityProvider + Send + Sync {
638 fn is_type_alias(&self, _code_unit: &CodeUnit) -> bool {
639 false
640 }
641}
642
643pub fn provider_declares_type_alias(
645 provider: Option<&dyn TypeAliasProvider>,
646 code_unit: &CodeUnit,
647) -> bool {
648 provider.is_some_and(|provider| provider.is_type_alias(code_unit))
649}
650
651pub trait TestDetectionProvider: CapabilityProvider {}
652
653#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
659pub enum DescendantIndexVariant {
660 WholeWorkspace,
662 ProductionOnly,
666}
667
668#[derive(Clone, Copy)]
685pub struct DescendantIndexScope<'a> {
686 cancellation: &'a CancellationToken,
687 excluded_source: Option<&'a dyn Fn(&ProjectFile) -> bool>,
688}
689
690impl<'a> DescendantIndexScope<'a> {
691 pub fn whole_workspace(cancellation: &'a CancellationToken) -> Self {
693 Self {
694 cancellation,
695 excluded_source: None,
696 }
697 }
698
699 pub fn excluding_sources(
703 cancellation: &'a CancellationToken,
704 excluded: &'a dyn Fn(&ProjectFile) -> bool,
705 ) -> Self {
706 Self {
707 cancellation,
708 excluded_source: Some(excluded),
709 }
710 }
711
712 pub fn cancellation(&self) -> &'a CancellationToken {
713 self.cancellation
714 }
715
716 pub fn variant(&self) -> DescendantIndexVariant {
717 match self.excluded_source {
718 Some(_) => DescendantIndexVariant::ProductionOnly,
719 None => DescendantIndexVariant::WholeWorkspace,
720 }
721 }
722
723 pub fn keep_going(&self) -> impl Fn() -> bool + use<'_> {
726 || !self.cancellation.is_cancelled()
727 }
728
729 pub fn admits(&self, declaration: &CodeUnit) -> bool {
731 self.excluded_source
732 .is_none_or(|excluded| !excluded(declaration.source()))
733 }
734}
735
736fn query_within_scope<T>(scope: &DescendantIndexScope<'_>, query: impl FnOnce() -> T) -> Option<T> {
737 (!scope.cancellation().is_cancelled()).then(query)
738}
739
740pub trait TypeHierarchyProvider: CapabilityProvider + Send + Sync {
741 fn get_direct_ancestors(&self, code_unit: &CodeUnit) -> Vec<CodeUnit>;
742 fn get_direct_descendants(&self, code_unit: &CodeUnit) -> HashSet<CodeUnit>;
743
744 fn supports_type_hierarchy(&self, code_unit: &CodeUnit) -> bool {
745 code_unit.is_class()
746 }
747
748 fn get_ancestors(&self, code_unit: &CodeUnit) -> Vec<CodeUnit> {
749 traverse_hierarchy(code_unit, |next| self.get_direct_ancestors(next))
750 }
751
752 fn get_descendants(&self, code_unit: &CodeUnit) -> Vec<CodeUnit> {
753 traverse_hierarchy(code_unit, |next| {
754 self.get_direct_descendants(next).into_iter().collect()
755 })
756 }
757
758 fn get_direct_ancestors_within(
767 &self,
768 code_unit: &CodeUnit,
769 scope: &DescendantIndexScope<'_>,
770 ) -> Option<Vec<CodeUnit>> {
771 query_within_scope(scope, || self.get_direct_ancestors(code_unit))
772 }
773
774 fn get_direct_descendants_within(
793 &self,
794 code_unit: &CodeUnit,
795 scope: &DescendantIndexScope<'_>,
796 ) -> Option<HashSet<CodeUnit>> {
797 query_within_scope(scope, || self.get_direct_descendants(code_unit))
798 }
799
800 fn get_descendants_within(
804 &self,
805 code_unit: &CodeUnit,
806 scope: &DescendantIndexScope<'_>,
807 ) -> Option<Vec<CodeUnit>> {
808 traverse_hierarchy_while(code_unit, scope.cancellation(), |next| {
809 self.get_direct_descendants_within(next, scope)
810 .map(|descendants| descendants.into_iter().collect())
811 })
812 }
813
814 fn get_polymorphic_matches<T: CodeUnitIndex>(
815 &self,
816 target: &CodeUnit,
817 analyzer: &T,
818 ) -> Vec<CodeUnit>
819 where
820 Self: Sized,
821 {
822 if !target.is_function() {
823 return Vec::new();
824 }
825
826 let Some(parent) = analyzer.parent_of(target) else {
827 return Vec::new();
828 };
829
830 self.get_descendants(&parent)
831 }
832}
833
834pub struct DirectDescendantIndex {
836 nodes: Box<[CodeUnit]>,
837 row_by_ancestor: HashMap<CodeUnit, u32>,
838 descendants: CompactRows<u32>,
839}
840
841impl DirectDescendantIndex {
842 pub fn from_indexed_nodes(
843 nodes: Vec<CodeUnit>,
844 index_by_node: HashMap<CodeUnit, u32>,
845 mut edges: Vec<(u32, u32)>,
846 ) -> Self {
847 normalize_indexed_edges(&nodes, &index_by_node, &mut edges);
848
849 let row_count = usize::from(!edges.is_empty())
850 + edges
851 .windows(2)
852 .filter(|pair| pair[0].0 != pair[1].0)
853 .count();
854 let mut row_by_ancestor = HashMap::default();
855 let mut descendants = CompactRowsBuilder::with_capacity(row_count, edges.len());
856 let mut cursor = 0;
857 while cursor < edges.len() {
858 let ancestor = edges[cursor].0;
859 let start = cursor;
860 while cursor < edges.len() && edges[cursor].0 == ancestor {
861 cursor += 1;
862 }
863 let row =
864 u32::try_from(descendants.rows()).expect("hierarchy index rows must fit in a u32");
865 row_by_ancestor.insert(nodes[ancestor as usize].clone(), row);
866 descendants.push_row(
867 edges[start..cursor]
868 .iter()
869 .map(|(_, descendant)| *descendant),
870 );
871 }
872 Self {
873 nodes: nodes.into_boxed_slice(),
874 row_by_ancestor,
875 descendants: descendants.finish(),
876 }
877 }
878
879 pub fn descendants(&self, ancestor: &CodeUnit) -> HashSet<CodeUnit> {
880 let Some(row) = self.row_by_ancestor.get(ancestor).copied() else {
881 return HashSet::default();
882 };
883 self.descendants
884 .row(row as usize)
885 .iter()
886 .map(|descendant| self.nodes[*descendant as usize].clone())
887 .collect()
888 }
889}
890
891pub fn descendants_from_variant_index(
900 index: &KeyedPoolSafeMemo<DescendantIndexVariant, DirectDescendantIndex>,
901 scope: &DescendantIndexScope<'_>,
902 code_unit: &CodeUnit,
903 build: impl Fn() -> Option<DirectDescendantIndex>,
904) -> Option<HashSet<CodeUnit>> {
905 Some(
906 index
907 .cell(&scope.variant())
908 .get_or_build_while(&scope.keep_going(), &build, &build)?
911 .descendants(code_unit),
912 )
913}
914
915pub fn build_direct_descendant_index<A, P>(
923 analyzer: &A,
924 provider: &P,
925 scope: &DescendantIndexScope<'_>,
926) -> Option<DirectDescendantIndex>
927where
928 A: CodeUnitIndex,
929 P: TypeHierarchyProvider + ?Sized,
930{
931 build_direct_descendant_index_from_candidates(
932 analyzer
933 .all_declarations()
934 .filter(|candidate| candidate.is_class() && scope.admits(candidate))
935 .collect(),
936 |candidate| provider.get_direct_ancestors_within(candidate, scope),
937 &scope.keep_going(),
938 )
939}
940
941pub fn build_direct_descendant_index_from_candidates<F>(
951 mut candidates: Vec<CodeUnit>,
952 mut direct_ancestors: F,
953 keep_going: &dyn Fn() -> bool,
954) -> Option<DirectDescendantIndex>
955where
956 F: FnMut(&CodeUnit) -> Option<Vec<CodeUnit>>,
957{
958 candidates.sort();
959 candidates.dedup();
960 let mut types_by_fq_name: HashMap<String, Vec<CodeUnit>> = HashMap::default();
961 for candidate in &candidates {
962 types_by_fq_name
963 .entry(candidate.fq_name())
964 .or_default()
965 .push(candidate.clone());
966 }
967 let mut nodes = candidates.clone();
968 let mut index_by_node: HashMap<_, _> = nodes
969 .iter()
970 .enumerate()
971 .map(|(index, node)| {
972 (
973 node.clone(),
974 u32::try_from(index).expect("hierarchy index declarations must fit in a u32"),
975 )
976 })
977 .collect();
978 let mut edges = Vec::new();
979 for candidate in candidates {
980 if !keep_going() {
981 return None;
982 }
983 let descendant = index_by_node[&candidate];
984 for ancestor in direct_ancestors(&candidate)? {
985 let ancestor = types_by_fq_name
986 .get(&ancestor.fq_name())
987 .and_then(|same_name| {
988 let mut same_source = same_name
989 .iter()
990 .filter(|unit| unit.source() == candidate.source());
991 let exact = same_source.next()?;
992 same_source.next().is_none().then(|| exact.clone())
993 })
994 .unwrap_or(ancestor);
995 let ancestor = *index_by_node.entry(ancestor.clone()).or_insert_with(|| {
996 let index = u32::try_from(nodes.len())
997 .expect("hierarchy index declarations must fit in a u32");
998 nodes.push(ancestor);
999 index
1000 });
1001 edges.push((ancestor, descendant));
1002 }
1003 }
1004 Some(DirectDescendantIndex::from_indexed_nodes(
1005 nodes,
1006 index_by_node,
1007 edges,
1008 ))
1009}
1010
1011fn traverse_hierarchy_while<F>(
1016 root: &CodeUnit,
1017 cancellation: &CancellationToken,
1018 mut next: F,
1019) -> Option<Vec<CodeUnit>>
1020where
1021 F: FnMut(&CodeUnit) -> Option<Vec<CodeUnit>>,
1022{
1023 let direct = next(root)?;
1024 if direct.is_empty() {
1025 return Some(Vec::new());
1026 }
1027
1028 let mut seen = BTreeSet::new();
1029 let mut result = Vec::new();
1030 let mut queue = VecDeque::new();
1031
1032 for item in direct {
1033 if seen.insert(item.fq_name()) {
1034 queue.push_back(item.clone());
1035 result.push(item);
1036 }
1037 }
1038
1039 while let Some(current) = queue.pop_front() {
1040 if cancellation.is_cancelled() {
1041 return None;
1042 }
1043 for item in next(¤t)? {
1044 if seen.insert(item.fq_name()) {
1045 queue.push_back(item.clone());
1046 result.push(item);
1047 }
1048 }
1049 }
1050
1051 Some(result)
1052}
1053
1054fn traverse_hierarchy<F>(root: &CodeUnit, mut next: F) -> Vec<CodeUnit>
1055where
1056 F: FnMut(&CodeUnit) -> Vec<CodeUnit>,
1057{
1058 let direct = next(root);
1059 if direct.is_empty() {
1060 return Vec::new();
1061 }
1062
1063 let mut seen = BTreeSet::new();
1064 let mut result = Vec::new();
1065 let mut queue = VecDeque::new();
1066
1067 for item in direct {
1068 if seen.insert(item.fq_name()) {
1069 queue.push_back(item.clone());
1070 result.push(item);
1071 }
1072 }
1073
1074 while let Some(current) = queue.pop_front() {
1075 for item in next(¤t) {
1076 if seen.insert(item.fq_name()) {
1077 queue.push_back(item.clone());
1078 result.push(item);
1079 }
1080 }
1081 }
1082
1083 result
1084}
1085
1086#[cfg(test)]
1087mod hierarchy_traversal_properties {
1088 use super::*;
1089 use crate::analyzer::model::CodeUnitType;
1090 use proptest::prelude::*;
1091 use std::collections::BTreeMap;
1092
1093 const NODES: usize = 8;
1094
1095 fn node(index: usize) -> CodeUnit {
1096 CodeUnit::new(
1097 ProjectFile::new(std::env::temp_dir(), "Hierarchy.java"),
1098 CodeUnitType::Class,
1099 "",
1100 format!("N{index}"),
1101 )
1102 }
1103
1104 fn index_of(unit: &CodeUnit) -> usize {
1105 unit.fq_name()[1..].parse().expect("test node name")
1106 }
1107
1108 fn graphs() -> impl Strategy<Value = Vec<Vec<usize>>> {
1110 proptest::collection::vec(proptest::collection::vec(0..NODES, 0..5), NODES)
1111 }
1112
1113 fn reference_distances(graph: &[Vec<usize>], root: usize) -> BTreeMap<usize, usize> {
1117 let mut distance: BTreeMap<usize, usize> = BTreeMap::new();
1118 for &next in &graph[root] {
1119 distance.insert(next, 1);
1120 }
1121 loop {
1122 let mut changed = false;
1123 for (from, edges) in graph.iter().enumerate() {
1124 let Some(&base) = distance.get(&from) else {
1125 continue;
1126 };
1127 for &to in edges {
1128 if distance.get(&to).is_none_or(|&known| known > base + 1) {
1129 distance.insert(to, base + 1);
1130 changed = true;
1131 }
1132 }
1133 }
1134 if !changed {
1135 return distance;
1136 }
1137 }
1138 }
1139
1140 proptest! {
1141 #![proptest_config(ProptestConfig::with_cases(128))]
1142
1143 #[test]
1148 fn visits_exactly_the_reachable_set_once_in_breadth_first_order(
1149 graph in graphs(),
1150 root in 0..NODES,
1151 ) {
1152 let mut calls: BTreeMap<usize, usize> = BTreeMap::new();
1153 let result = traverse_hierarchy(&node(root), |unit| {
1154 let id = index_of(unit);
1155 *calls.entry(id).or_default() += 1;
1156 graph[id].iter().map(|&to| node(to)).collect()
1157 });
1158 let found: Vec<usize> = result.iter().map(index_of).collect();
1159
1160 let distance = reference_distances(&graph, root);
1161 let unique: BTreeSet<usize> = found.iter().copied().collect();
1162 prop_assert_eq!(found.len(), unique.len(), "a declaration was returned twice: {:?}", found);
1163 prop_assert_eq!(unique, distance.keys().copied().collect::<BTreeSet<_>>());
1164 prop_assert!(
1165 found.windows(2).all(|pair| distance[&pair[0]] <= distance[&pair[1]]),
1166 "not breadth-first: {:?} with distances {:?}", found, distance
1167 );
1168 prop_assert!(
1171 calls.iter().all(|(&id, &count)| count == 1 || (id == root && count == 2)),
1172 "repeated expansion: {:?}", calls
1173 );
1174
1175 let live = CancellationToken::new();
1177 let guarded = traverse_hierarchy_while(&node(root), &live, |unit| {
1178 Some(graph[index_of(unit)].iter().map(|&to| node(to)).collect())
1179 });
1180 prop_assert_eq!(guarded, Some(result));
1181 }
1182
1183 #[test]
1187 fn guarded_traversal_never_returns_a_partial_answer(
1188 graph in graphs(),
1189 root in 0..NODES,
1190 fail_on in 0..NODES,
1191 ) {
1192 let reachable = reference_distances(&graph, root);
1193 let failing = traverse_hierarchy_while(&node(root), &CancellationToken::new(), |unit| {
1194 let id = index_of(unit);
1195 (id != fail_on).then(|| graph[id].iter().map(|&to| node(to)).collect())
1196 });
1197 let requested = fail_on == root || reachable.contains_key(&fail_on);
1200 prop_assert_eq!(failing.is_none(), requested);
1201
1202 let cancelled = CancellationToken::new();
1203 cancelled.cancel();
1204 let stopped = traverse_hierarchy_while(&node(root), &cancelled, |unit| {
1205 Some(graph[index_of(unit)].iter().map(|&to| node(to)).collect())
1206 });
1207 prop_assert_eq!(stopped.is_none(), !graph[root].is_empty());
1208 if graph[root].is_empty() {
1209 prop_assert_eq!(stopped, Some(Vec::new()));
1210 }
1211 }
1212 }
1213}