Skip to main content

brokk_bifrost_core/analyzer/
capabilities.rs

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/// File-local facts consumed together while constructing the coarse direct
21/// dependency graph.
22///
23/// `contains_tests` is optional so providers without a bulk test-classification
24/// projection can retain their existing per-file fallback. Tree-sitter-backed
25/// providers populate it from the same persisted blob metadata read that
26/// supplies their import facts.
27#[derive(Debug, Clone, PartialEq, Eq)]
28pub struct FileDependencyFacts {
29    pub imports: Vec<ImportInfo>,
30    pub contains_tests: Option<bool>,
31}
32
33/// Structured direct file dependencies contributed outside ordinary imports.
34///
35/// `complete` belongs to the relation set rather than to cancellation. A
36/// provider may know useful edges while lacking enough build-model evidence to
37/// prove that it found every edge; callers must preserve those edges without
38/// publishing the result as a complete cached graph.
39#[derive(Debug, Clone, PartialEq, Eq)]
40pub struct AdditionalFileDependencies {
41    /// Optional structured cause when membership discovery cannot close this set.
42    pub membership_cause: Option<CSharpCompilationMembershipOpenCause>,
43    pub dependencies: HashMap<ProjectFile, HashSet<ProjectFile>>,
44    pub complete: bool,
45}
46
47/// Discovery evidence for exhaustive C# source-to-compilation membership.
48/// This is process-local evidence, not a persisted compilation fact.
49#[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    /// A project file the listing omitted and configuration capture did not
68    /// read. The reason is that omission's typed cause. The file is unknown,
69    /// not missing.
70    ProjectFileUnknown(crate::analyzer::project::WorkspaceFileOmissionReason),
71    ListingUnavailable,
72}
73
74/// One structured name lookup performed while resolving a file's imports.
75/// Candidate invalidation is indexed by the consulted file and looked-up name
76/// so a content edit can invalidate only importers whose resolution consulted
77/// the changed binding. The name `*` is reserved for a glob-surface lookup.
78#[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/// Positive and negative structured lookups used to resolve one importer's
86/// file edges. Missing module keys let a newly appearing module invalidate
87/// imports that could not resolve before it existed.
88#[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/// One effective Rust name binding in a source file's module surface.
95///
96/// These rows are computed only for changed files and persisted relationally
97/// so the import graph can compare old and new lookup surfaces without
98/// retaining a workspace-sized Rust index in memory.
99#[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/// Fixed-width fingerprints of the structured inputs to one file's effective
113/// import bindings. These are cache identities, not serialized fact bundles.
114#[derive(Debug, Clone, Copy, PartialEq, Eq)]
115pub struct ImportGraphInputDigests {
116    pub binding_surface: [u8; 32],
117    pub import_rows: [u8; 32],
118}
119
120/// Target-file edges with structured provenance values for each target.
121pub type ImportedFileEdgeTargets = HashMap<ProjectFile, Vec<Value>>;
122
123/// File targets resolved for one import statement. Providers with complete
124/// candidate dependencies emit these separately so an edit can replace only
125/// the statements whose lookup routes consulted the changed file.
126#[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
156/// Wrap a freshly built imported set without charging it.
157pub 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    /// Shared, not owned: every memoizing implementation already stores the set
165    /// behind an `Arc` in its per-file cache, and the hottest consumers only
166    /// read it (a membership test in candidate discovery, a projection to
167    /// source files in the reverse-import index). Returning the `Arc` removes a
168    /// whole-set clone per cache hit and per insert.
169    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    /// Return the union of workspace files that reference any `target`.
176    ///
177    /// A depth-bounded caller already knows both sets and must not be forced to
178    /// initialize a provider's whole-workspace reverse index once per target.
179    /// Providers with a structured batch representation can override this.
180    /// The default preserves the file-at-a-time result for every existing
181    /// provider.
182    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    /// Return import facts for a group of files without requiring each caller
198    /// to hydrate a complete per-file analyzer state. `None` preserves the
199    /// existing file-at-a-time behavior for providers without a bulk read model.
200    fn import_infos_for_files(
201        &self,
202        _files: &[ProjectFile],
203    ) -> Option<HashMap<ProjectFile, Vec<ImportInfo>>> {
204        None
205    }
206
207    /// Return the file-local facts needed by coarse dependency-graph
208    /// construction in one batch.
209    ///
210    /// The default preserves providers that only expose bulk imports. A
211    /// provider with persisted test classification should override this so a
212    /// reverse walk does not rehydrate one file state per reached graph node.
213    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    /// Whether this provider can produce complete structured negative and
234    /// positive import lookup dependencies for every source it analyzes.
235    fn has_complete_import_resolution_dependencies(&self) -> bool {
236        false
237    }
238
239    /// Stable module-path keys backed or declared by this source. They are
240    /// used only to match persisted missing-module lookups after source-set
241    /// changes.
242    fn import_graph_module_path_keys_for_files(
243        &self,
244        _files: &[ProjectFile],
245    ) -> Option<HashMap<ProjectFile, Vec<String>>> {
246        None
247    }
248
249    /// Return the current structured module-level binding surface for the
250    /// selected files. Incremental providers use this to invalidate only the
251    /// names whose bindings changed after a source edit.
252    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    /// Return per-file hashes of the structured declarations/routes and import
261    /// binders that can affect the file's import-graph surface. A provider that
262    /// cannot prove completeness returns None, selecting conservative refresh.
263    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    /// Return complete structured candidate dependencies for each importer.
272    /// Providers without this evidence return None; callers can still build
273    /// correct edges, but must use conservative full invalidation when those
274    /// providers' source contents or source sets change.
275    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    /// Resolve structured import edges while retaining the source import
285    /// ordinal. `selected_ordinals` lists imports to resolve for files whose
286    /// other import rows will be carried forward; files absent from that map
287    /// are resolved in full. Providers without per-import output return None
288    /// for a partial request, allowing the caller to use its conservative
289    /// source-level path.
290    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    /// Recompute only the candidate dependencies for selected import
318    /// ordinals. The default is conservative: it can only provide all facts
319    /// when the caller did not select a subset.
320    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    /// Return structured direct file dependencies that are not represented by
334    /// ordinary import facts.
335    ///
336    /// Rust external-module declarations are the motivating case: `mod x;`
337    /// makes the declaring file depend on `x.rs`, but it is neither a `use`
338    /// declaration nor an `extern crate` declaration. Providers should return
339    /// `None` when cancellation prevents a complete answer; callers must not
340    /// cache that prefix as a complete graph.
341    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    /// The file's import facts, which fall through to the import-tier store
350    /// read when nothing retained answers. Crossing that tier is only cheap
351    /// under an open request scope, so the caller proves one is open by
352    /// passing a [`QueryToken`] (issue #2423).
353    fn import_info_of(&self, _token: QueryToken<'_>, _file: &ProjectFile) -> Vec<ImportInfo> {
354        Vec::new()
355    }
356
357    /// Return the complete, unbounded import set for `file` when the provider
358    /// can prove that its source-owned import publication is available.
359    /// `Some(Vec::new())` is an authoritative import-free file; `None` means
360    /// that the file's import facts are unavailable and must not be treated as
361    /// an empty set.  The legacy [`Self::import_info_of`] method intentionally
362    /// retains its recovery semantics for callers that cannot preserve this
363    /// distinction.
364    fn import_info_of_checked(
365        &self,
366        _token: QueryToken<'_>,
367        _file: &ProjectFile,
368    ) -> Option<Vec<ImportInfo>> {
369        None
370    }
371
372    /// Resolve imported source units from already-loaded import facts. Providers
373    /// that cannot do this cheaply return `None` and use `imported_code_units_of`.
374    fn imported_code_units_from_infos(
375        &self,
376        _file: &ProjectFile,
377        _imports: &[ImportInfo],
378    ) -> Option<Arc<HashSet<CodeUnit>>> {
379        None
380    }
381
382    /// Resolve directly imported project files from already-loaded import facts.
383    /// Providers that do not expose file-level edges return `None` and callers
384    /// can derive a conservative approximation from imported declarations.
385    fn imported_files_from_infos(
386        &self,
387        _file: &ProjectFile,
388        _imports: &[ImportInfo],
389    ) -> Option<HashSet<ProjectFile>> {
390        None
391    }
392
393    /// Provenance for file edges resolved from these structured import facts.
394    /// Providers with richer resolution routes can attach those routes to the
395    /// target file; `None` leaves the caller to use the general structured
396    /// import facts as provenance.
397    fn imported_file_edge_provenance_from_infos(
398        &self,
399        _file: &ProjectFile,
400        _imports: &[ImportInfo],
401    ) -> Option<ImportedFileEdgeTargets> {
402        None
403    }
404
405    /// Resolve each file's imports while streaming results to `visit`, so a
406    /// provider can reuse request-scoped resolver state without retaining a
407    /// workspace-sized result collection. Return `None` only when unsupported;
408    /// in that case `visit` must not have been called. Return `Some(())` after
409    /// handling files until the input ends or `visit` returns `false`.
410    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    /// Stream resolved file edges together with their structured provenance.
421    /// The default preserves providers that only expose targets and records
422    /// the parsed import facts that were supplied for each importer.
423    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    /// Whether `source_file` can reference a declaration of `target`. A `true`
459    /// is an answer; a `false` is only an absence of evidence, which is why
460    /// callers still run the expansion backstop after one. Providers that can
461    /// prove the negative override [`Self::import_reachability`] instead and
462    /// derive this from it.
463    fn could_import_file(
464        &self,
465        _source_file: &ProjectFile,
466        _imports: &[ImportInfo],
467        _target: &ProjectFile,
468    ) -> bool {
469        false
470    }
471
472    /// Resolve, in one batch, whatever [`Self::could_import_file`] would look
473    /// up once per candidate.
474    ///
475    /// The shared import-graph candidate walk visits every workspace file, so
476    /// a provider that answers each visit with its own store lookup pays that
477    /// lookup once per import statement in the workspace -- 397k to 662k
478    /// `definition_candidates` round trips inside a single `scan_usages`
479    /// query on a 35k-file Rust workspace (#1748). The walk knows its whole
480    /// candidate set before it inspects any of it, so this hook lets the
481    /// provider enumerate its keys up front and collapse them into batched
482    /// reads.
483    ///
484    /// Doing nothing is always correct: the per-candidate path still answers
485    /// exactly as before, just without the shared warm result. Providers whose
486    /// per-candidate answer is already file-local (Python, JS/TS, Go, C++)
487    /// keep the default.
488    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    /// Batch the definition identities that file-dependency resolution will
497    /// consult after import facts have been loaded for a whole workspace.
498    ///
499    /// This is separate from [`Self::prefetch_import_targets`]: exact usage
500    /// candidate discovery and coarse file-edge construction do not
501    /// necessarily resolve the same names. Providers whose file resolver is
502    /// already path-local keep the no-op default.
503    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    /// The three-valued form of [`Self::could_import_file`], which lets a
512    /// provider that has a completeness proof retire the caller's backstop.
513    ///
514    /// The default preserves the historical contract exactly by mapping the
515    /// bool spelling's `true` to [`ImportReachability::Reaches`] and its
516    /// `false` to [`ImportReachability::Unknown`] -- never to `DoesNotReach`,
517    /// because the bool contract never distinguished "no" from "I did not
518    /// find one".
519    ///
520    /// Bridging runs in this direction only. A provider overrides this method
521    /// and defines `could_import_file` over it, so the two spellings cannot
522    /// drift apart.
523    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/// How completely a provider can answer "can `source_file` reference a
538/// declaration of `target`?".
539///
540/// Candidate discovery asks this per (candidate, target) pair and, when it
541/// gets no positive answer, materializes every declaration the candidate
542/// imports as a recall backstop. For a namespace-import language that
543/// expansion is the whole workspace's top-level types per using directive,
544/// which is the shape that burned #1194. The backstop exists only because the
545/// bool contract could not distinguish a proven "no" from an unproven one.
546///
547/// A provider must return `DoesNotReach` only from a proof that covers every
548/// way its language can name a declaration without importing it. Anything less
549/// is `Unknown`: the cost of an unnecessary expansion is time, the cost of a
550/// wrong `DoesNotReach` is a missing usage.
551#[derive(Debug, Clone, Copy, PartialEq, Eq)]
552pub enum ImportReachability {
553    /// The candidate can reference the target. Accept it without expanding.
554    Reaches,
555    /// The candidate provably cannot. Reject it without expanding.
556    DoesNotReach,
557    /// Undecided. The caller runs its own backstop, exactly as before this
558    /// verdict existed.
559    Unknown,
560}
561
562/// Resolve direct project-file edges from structured import facts. Prefer a
563/// provider's file-level resolver so imports whose target has no declarations
564/// remain visible; otherwise conservatively project resolved declaration
565/// identities back to their source files.
566pub 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
681/// `Send + Sync` like its three sibling capabilities: every implementor is an
682/// analyzer, and a parallel whole-workspace scan holds the provider across its
683/// fan-out (`kotlin_graph`'s edge builder does exactly that).
684pub trait TypeAliasProvider: CapabilityProvider + Send + Sync {
685    fn is_type_alias(&self, _code_unit: &CodeUnit) -> bool {
686        false
687    }
688}
689
690/// Whether a capability provider classifies `code_unit` as a type alias.
691pub 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/// Which slice of the workspace a descendant index covers.
701///
702/// This is the memo key, and two values is the whole range: the excluded set is
703/// a pure function of the analyzer and the file, so every request that asks to
704/// leave test files out describes the same index.
705#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
706pub enum DescendantIndexVariant {
707    /// Every class-like declaration the analyzer indexes.
708    WholeWorkspace,
709    /// The declarations whose source file the caller's predicate rejected are
710    /// left out. In practice that is a `scan_usages` request with
711    /// `include_tests: false`, whose test files the answer would discard anyway.
712    ProductionOnly,
713}
714
715/// An exclusion decision could not be established. The caller retains the
716/// underlying diagnostic; index builders must stop without publishing an index.
717#[derive(Debug, Clone, Copy, PartialEq, Eq)]
718pub struct SourceExclusionUnavailable;
719
720/// A source exclusion decision, with availability preserved across crate boundaries.
721pub type SourceExclusionPredicate<'a> =
722    dyn Fn(&ProjectFile) -> Result<bool, SourceExclusionUnavailable> + 'a;
723
724/// The request state a whole-workspace descendant-index build needs: the
725/// deadline it polls, and the slice of the workspace it covers.
726///
727/// The two travel together because one loop consumes both -- the per-class loop
728/// in [`build_direct_descendant_index_from_candidates`] and, for C++, the
729/// per-file include-closure walk beneath it -- and because the slice is the
730/// memo key that the deadline's complete-or-nothing rule is applied to.
731///
732/// The exclusion predicate is supplied by the caller rather than named here.
733/// Test classification needs an analyzer (`file_is_test_only` reads a language
734/// module index), which this crate must not know about; the closure crossing is
735/// the same one the Rust usage walks already use for their `keep_going`
736/// predicate. **The predicate must be a pure function of the analyzer and the
737/// file.** That is the condition that makes [`DescendantIndexVariant`] a
738/// complete key: two requests that both exclude test files must describe the
739/// same index, or one would be served the other's. An unavailable decision
740/// invalidates the entire build: never cache that index under ProductionOnly.
741#[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    /// Every class in the workspace, stopping when `cancellation` says to.
749    pub fn whole_workspace(cancellation: &'a CancellationToken) -> Self {
750        Self {
751            cancellation,
752            excluded_source: None,
753        }
754    }
755
756    /// Every class whose source file `excluded` rejects is left out of the
757    /// index entirely -- it is never handed to `get_direct_ancestors`, so the
758    /// per-file resolution work behind that call is never charged.
759    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    /// The poll predicate for a builder that would rather take a plain
781    /// `Fn() -> bool` than a token.
782    pub fn keep_going(&self) -> impl Fn() -> bool + use<'_> {
783        || !self.cancellation.is_cancelled()
784    }
785
786    /// Whether `declaration` belongs in this index.
787    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/// A caller's hierarchy query was stopped. Shared by both traversal directions.
796#[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/// One member shape fixed by a platform language specification.
811#[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/// Language rules for an interface's lookup-only member root.
819/// This inventory supplies no nominal inheritance or protected-access proof.
820#[derive(Debug)]
821pub struct ImplicitInterfaceMembers {
822    pub owner: &'static str,
823    pub simple_name: &'static str,
824    /// Some is a fixed language inventory. None requires exact selected
825    /// public instance method authority; it never grants an unknown member.
826    pub methods: Option<&'static [PlatformInventoryMethod]>,
827    pub declaration: Option<ImplicitMemberDeclarationRules>,
828}
829
830/// Optional declaration synthesis supplied by a language specification.
831/// Without this rule a lookup root retains the selected member's real owner
832/// and modifiers. Java's implicit interface declarations use this rule.
833#[derive(Debug)]
834pub struct ImplicitMemberDeclarationRules {
835    pub visibility: crate::analyzer::structural::resolution::DeclaredVisibility,
836    pub is_abstract: bool,
837}
838
839/// One declared parameter type of a nominal-family member, resolved and
840/// erased (JLS 4.6) from the declaration's own type node.
841///
842/// Override matching compares these per position (JLS 8.4.2, 8.4.8.1). A type
843/// variable of the member's *owner* keeps its index, because a subtype that
844/// names the owner with type arguments substitutes them before erasure
845/// (`compareTo(T)` in `Comparable<Box>` is `compareTo(Box)`). Any other type
846/// variable is replaced by the erasure of its leftmost bound.
847#[derive(Debug, Clone, PartialEq, Eq)]
848pub enum MemberFamilyParameterType {
849    /// A primitive type, by keyword.
850    Primitive(String),
851    /// A nominal type whose fully qualified name is known.
852    Nominal(String),
853    /// A nominal type whose identity the analyzer could not establish. It
854    /// carries every fully qualified name the language's name tiers could give
855    /// the spelling at its use site, strongest first, and the type is one of
856    /// them. Two equal lists are the same type, because the tiers pick from a
857    /// list by a rule of its inputs; two disjoint lists are different types.
858    /// An empty list is a type that could not be read at all.
859    Unresolved(Vec<String>),
860    Array(Box<MemberFamilyParameterType>),
861    /// The owner's type parameter at `index`, with the erasure of its bound.
862    OwnerTypeParameter {
863        index: usize,
864        erasure: Box<MemberFamilyParameterType>,
865    },
866}
867
868/// The type arguments a subtype's declaration passes to one direct supertype,
869/// each as a [`MemberFamilyParameterType`] in the subtype's scope.
870#[derive(Debug, Clone, PartialEq, Eq)]
871pub enum MemberFamilySupertypeArguments {
872    /// The supertype is named raw (or is not generic): its members are erased.
873    Raw,
874    Arguments(Vec<MemberFamilyParameterType>),
875    /// The clause naming the supertype could not be read or singled out.
876    Unknown,
877}
878
879/// An ancestor whose member declarations the workspace did not read.
880#[derive(Debug, Clone, PartialEq, Eq)]
881pub struct UnreadMemberFamilyAncestor {
882    pub name: String,
883    pub inventory: Option<&'static [PlatformInventoryMethod]>,
884}
885
886#[derive(Debug, Default)]
887pub struct MemberFamilyAncestors {
888    pub resolved: Vec<CodeUnit>,
889    pub ambiguous: Vec<Vec<CodeUnit>>,
890    pub unread: Vec<UnreadMemberFamilyAncestor>,
891}
892
893/// Evidence that a hierarchy query could not close its search boundary.
894#[derive(Debug, Clone, PartialEq, Eq)]
895pub enum HierarchyOpenReason {
896    /// Existing hierarchy diagnostics, including `HierarchyTruncated` and
897    /// `AncestorExternalUnindexed`, retain their consumer-side vocabulary.
898    MemberFamily(crate::analyzer::structural::resolution::MemberFamilyReason),
899    /// The descendant index could not acquire the evidence needed to fill.
900    DescendantIndexUnavailable,
901    /// Forward structural-satisfaction coverage (interfaces a type satisfies
902    /// without embedding them) is not closed.
903    ForwardSatisfactionIncomplete,
904    /// Preserve the unread name and any language-specified member inventory.
905    UnreadAncestor(UnreadMemberFamilyAncestor),
906    /// A descendant index was built, but these candidates' own ancestor
907    /// answers are open: any of them may be a descendant of the queried type
908    /// through an ancestor the language could not close. The definite edges
909    /// beside this reason are still correct.
910    OpenAncestorCandidates(Vec<CodeUnit>),
911    /// A supertype clause of `declared_by` names `name`, and the language's
912    /// type lookup finds no indexed declaration for it: a library type read
913    /// from an assembly, for example. When `may_name_indexed` is false the
914    /// language proved the clause names a type outside the index, so the
915    /// definite edges still name every indexed ancestor; when it is true the
916    /// lookup failure proves nothing about indexed types.
917    ExternalUnindexedAncestor {
918        name: String,
919        declared_by: CodeUnit,
920        may_name_indexed: bool,
921    },
922    /// Source could not establish the supertype clauses of `declared_by`, so
923    /// the definite edges may omit any ancestor.
924    SupertypesUnread { declared_by: CodeUnit },
925}
926
927impl HierarchyOpenReason {
928    /// Stable reason label with the boundary name retained as data.
929    pub fn description(&self) -> String {
930        match self {
931            Self::UnreadAncestor(ancestor) => format!("{}: {}", self.as_str(), ancestor.name),
932            Self::OpenAncestorCandidates(candidates) => {
933                let names: Vec<String> = candidates.iter().map(CodeUnit::fq_name).collect();
934                format!("{}: {}", self.as_str(), names.join(", "))
935            }
936            Self::ExternalUnindexedAncestor { name, .. } => format!("{}: {name}", self.as_str()),
937            _ => self.as_str().to_string(),
938        }
939    }
940
941    /// Whether the work behind this reason stopped short, as opposed to
942    /// finishing with a closed-world gap. An index builder keeps its positive
943    /// edges and treats the declaration as an unbounded open candidate; the
944    /// caller retains the stop receipt and decides whether to memoize it.
945    pub fn stopped_short(&self) -> bool {
946        matches!(
947            self,
948            Self::DescendantIndexUnavailable
949                | Self::MemberFamily(
950                    crate::analyzer::structural::resolution::MemberFamilyReason::HierarchyTruncated
951                        | crate::analyzer::structural::resolution::MemberFamilyReason::ProviderUnavailable
952                )
953        )
954    }
955
956    /// Stable public reason label, shared by hierarchy presentation surfaces.
957    pub fn as_str(&self) -> &'static str {
958        match self {
959            Self::MemberFamily(reason) => reason.label(),
960            Self::DescendantIndexUnavailable => "descendant_index_unavailable",
961            Self::ForwardSatisfactionIncomplete => "forward_satisfaction_incomplete",
962            Self::UnreadAncestor(_) => "unread_ancestor",
963            Self::OpenAncestorCandidates(_) => "open_ancestor_candidates",
964            Self::ExternalUnindexedAncestor { .. } => {
965                crate::analyzer::structural::resolution::MemberFamilyReason::AncestorExternalUnindexed
966                    .label()
967            }
968            Self::SupertypesUnread { .. } => "supertypes_unread",
969        }
970    }
971
972    /// The declaration whose supertype clauses left the answer open, when the
973    /// reason names one.
974    pub fn declared_by(&self) -> Option<&CodeUnit> {
975        match self {
976            Self::ExternalUnindexedAncestor { declared_by, .. }
977            | Self::SupertypesUnread { declared_by } => Some(declared_by),
978            _ => None,
979        }
980    }
981
982    /// Whether the definite edges still name every indexed ancestor, so the
983    /// inverse (descendant) relation over indexed types built from them is
984    /// exact. Only a clause proven to name a type outside the index
985    /// qualifies.
986    pub fn keeps_indexed_edges_exact(&self) -> bool {
987        matches!(
988            self,
989            Self::ExternalUnindexedAncestor {
990                may_name_indexed: false,
991                ..
992            }
993        )
994    }
995}
996
997/// A hierarchy answer owned by one request. Never retain it in a memo or cache.
998///
999/// Only `edges` are definite. Each ambiguous group contains alternatives for
1000/// one unresolved edge; none of those alternatives is a definite ancestor or
1001/// descendant. Ambiguity and open reasons both prevent an exhaustive answer.
1002#[derive(Debug, Clone, PartialEq, Eq)]
1003pub struct HierarchyAnswer<T = CodeUnit> {
1004    pub edges: Vec<T>,
1005    pub ambiguous: Vec<Vec<T>>,
1006    pub open: Vec<HierarchyOpenReason>,
1007}
1008
1009impl<T> HierarchyAnswer<T> {
1010    /// Construct a complete answer, preserving the provider's edge order.
1011    pub fn complete(edges: Vec<T>) -> Self {
1012        Self {
1013            edges,
1014            ambiguous: Vec::new(),
1015            open: Vec::new(),
1016        }
1017    }
1018
1019    /// Unavailable facts must name their gap explicitly.
1020    pub fn incomplete(reason: HierarchyOpenReason) -> Self {
1021        Self {
1022            edges: Vec::new(),
1023            ambiguous: Vec::new(),
1024            open: vec![reason],
1025        }
1026    }
1027
1028    /// Union definite edges in CodeUnit order while retaining all uncertainty.
1029    pub fn merge(&mut self, other: Self)
1030    where
1031        T: Ord,
1032    {
1033        self.edges.extend(other.edges);
1034        self.edges.sort();
1035        self.edges.dedup();
1036        self.ambiguous.extend(other.ambiguous);
1037        self.open.extend(other.open);
1038    }
1039
1040    pub fn is_complete(&self) -> bool {
1041        self.ambiguous.is_empty() && self.open.is_empty()
1042    }
1043
1044    /// Whether the query stopped short (see [`HierarchyOpenReason::stopped_short`]).
1045    pub fn stopped_short(&self) -> bool {
1046        self.open.iter().any(HierarchyOpenReason::stopped_short)
1047    }
1048
1049    /// Whether the definite edges name every indexed ancestor, so an inverse
1050    /// (descendant) relation over indexed types built from them is exact. An
1051    /// answer whose only open reasons name types outside the index qualifies.
1052    pub fn keeps_indexed_edges_exact(&self) -> bool {
1053        self.ambiguous.is_empty()
1054            && self
1055                .open
1056                .iter()
1057                .all(HierarchyOpenReason::keeps_indexed_edges_exact)
1058    }
1059
1060    /// Lossy: drops ambiguous groups and open reasons. Only for callers whose
1061    /// language answers are complete by construction.
1062    pub fn definite(&self) -> &[T] {
1063        &self.edges
1064    }
1065}
1066
1067/// One caller-owned hierarchy session, borrowed by every step of a walk.
1068/// The handle has one borrower and is never shared between Rayon tasks.
1069pub trait HierarchyQuery {
1070    fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1071    fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1072    fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors;
1073
1074    fn direct_ancestors_within(
1075        &mut self,
1076        unit: &CodeUnit,
1077        scope: &DescendantIndexScope<'_>,
1078    ) -> Result<HierarchyAnswer, Cancelled> {
1079        query_within_scope(scope, || self.direct_ancestors(unit))
1080    }
1081
1082    fn direct_descendants_within(
1083        &mut self,
1084        unit: &CodeUnit,
1085        scope: &DescendantIndexScope<'_>,
1086    ) -> Result<HierarchyAnswer, Cancelled> {
1087        query_within_scope(scope, || self.direct_descendants(unit))
1088    }
1089}
1090
1091/// Compatibility adapter for providers whose direct reads need no session.
1092/// Each method forwards to the original provider, including scoped overrides.
1093pub struct ForwardingHierarchyQuery<'a, P: ?Sized>(pub &'a P);
1094
1095impl<P: TypeHierarchyProvider + ?Sized> HierarchyQuery for ForwardingHierarchyQuery<'_, P> {
1096    fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1097        self.0.get_direct_ancestors(unit)
1098    }
1099    fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1100        self.0.get_direct_descendants(unit)
1101    }
1102    fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors {
1103        self.0.member_family_ancestors(unit)
1104    }
1105    fn direct_ancestors_within(
1106        &mut self,
1107        unit: &CodeUnit,
1108        scope: &DescendantIndexScope<'_>,
1109    ) -> Result<HierarchyAnswer, Cancelled> {
1110        self.0.get_direct_ancestors_within(unit, scope)
1111    }
1112    fn direct_descendants_within(
1113        &mut self,
1114        unit: &CodeUnit,
1115        scope: &DescendantIndexScope<'_>,
1116    ) -> Result<HierarchyAnswer, Cancelled> {
1117        self.0.get_direct_descendants_within(unit, scope)
1118    }
1119}
1120
1121pub trait TypeHierarchyProvider: Send + Sync {
1122    /// Invoke the walk once with a request-local hierarchy handle.
1123    fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1124        run(&mut ForwardingHierarchyQuery(self));
1125    }
1126
1127    /// Root-aware entry lets workspace dispatch exclude unrelated delegates.
1128    /// Providers without workspace routing use their ordinary query boundary.
1129    fn with_hierarchy_query_for(
1130        &self,
1131        _root: &CodeUnit,
1132        run: &mut dyn FnMut(&mut dyn HierarchyQuery),
1133    ) {
1134        self.with_hierarchy_query(run);
1135    }
1136
1137    fn get_direct_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1138    fn get_direct_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1139
1140    /// The nominal member walk also needs the ancestors not represented by
1141    /// workspace declarations. Languages opt in without changing type lookup.
1142    /// The default names each clause the provider reported as outside the
1143    /// index as an unread ancestor without an inventory, so a family that
1144    /// reaches it stays open under that ancestor's name (#7363).
1145    fn member_family_ancestors(&self, owner: &CodeUnit) -> MemberFamilyAncestors {
1146        let answer = self.get_direct_ancestors(owner);
1147        MemberFamilyAncestors {
1148            resolved: answer.edges,
1149            ambiguous: answer.ambiguous,
1150            unread: answer
1151                .open
1152                .into_iter()
1153                .filter_map(|reason| match reason {
1154                    HierarchyOpenReason::ExternalUnindexedAncestor { name, .. } => {
1155                        Some(UnreadMemberFamilyAncestor {
1156                            name,
1157                            inventory: None,
1158                        })
1159                    }
1160                    _ => None,
1161                })
1162                .collect(),
1163        }
1164    }
1165
1166    /// Whether an unread ancestor's complete method inventory can declare
1167    /// `member`. A method of another name never can. Parameter evidence from
1168    /// the language narrows further; without it the side stays open.
1169    fn member_family_inventory_matches(
1170        &self,
1171        member: &CodeUnit,
1172        inventory: &[PlatformInventoryMethod],
1173    ) -> bool {
1174        let methods: Vec<_> = inventory
1175            .iter()
1176            .filter(|method| method.name == member.identifier())
1177            .collect();
1178        if methods.is_empty() {
1179            return false;
1180        }
1181        let Some(arity) = self.member_family_parameter_arity(member) else {
1182            return true;
1183        };
1184        let methods: Vec<_> = methods
1185            .into_iter()
1186            .filter(|method| method.parameters.len() == arity)
1187            .collect();
1188        if methods.is_empty() {
1189            return false;
1190        }
1191        if methods.iter().any(|method| method.parameters.is_empty()) {
1192            return true;
1193        }
1194        let Some(parameters) = self.member_family_erased_parameters(member) else {
1195            return true;
1196        };
1197        methods.iter().any(|method| {
1198            parameters
1199                .iter()
1200                .map(String::as_str)
1201                .eq(method.parameters.iter().copied())
1202        })
1203    }
1204
1205    /// The member's declared parameter count, when the language knows it.
1206    fn member_family_parameter_arity(&self, _member: &CodeUnit) -> Option<usize> {
1207        None
1208    }
1209
1210    /// The member's parameter types resolved and erased the way the platform
1211    /// inventory spells them, when the language can resolve them.
1212    fn member_family_erased_parameters(&self, _member: &CodeUnit) -> Option<Vec<String>> {
1213        None
1214    }
1215
1216    /// The member's declared parameter types for override matching, or `None`
1217    /// when the language does not read them structurally. The shared walk then
1218    /// falls back to the recorded parameter spellings, which can confirm an
1219    /// override but never refute one.
1220    fn member_family_parameter_types(
1221        &self,
1222        _member: &CodeUnit,
1223    ) -> Option<Vec<MemberFamilyParameterType>> {
1224        None
1225    }
1226
1227    /// The type arguments `subtype` passes to its direct supertype `supertype`.
1228    fn member_family_supertype_arguments(
1229        &self,
1230        _subtype: &CodeUnit,
1231        _supertype: &CodeUnit,
1232    ) -> MemberFamilySupertypeArguments {
1233        MemberFamilySupertypeArguments::Unknown
1234    }
1235
1236    fn supports_type_hierarchy(&self, code_unit: &CodeUnit) -> bool {
1237        code_unit.is_class()
1238    }
1239
1240    fn get_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1241        let mut result = None;
1242        self.with_hierarchy_query_for(code_unit, &mut |query| {
1243            result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1244                query.direct_ancestors(next)
1245            }));
1246        });
1247        result.expect("hierarchy query callback runs once")
1248    }
1249
1250    fn get_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1251        let mut result = None;
1252        self.with_hierarchy_query_for(code_unit, &mut |query| {
1253            result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1254                query.direct_descendants(next)
1255            }));
1256        });
1257        let mut answer = result.expect("hierarchy query callback runs once");
1258        answer.edges.sort();
1259        answer
1260    }
1261
1262    /// [`Self::get_direct_ancestors`] under a caller's deadline.
1263    ///
1264    /// `Err(Cancelled)` means the resolution stopped short; it is never an empty answer,
1265    /// which stays the honest way to say "no resolvable base types". The
1266    /// default checks the deadline once and delegates, which is right for a
1267    /// provider whose ancestor resolution is a lookup. C++ overrides it because
1268    /// resolving one class's bases means walking that file's whole transitive
1269    /// `#include` closure.
1270    fn get_direct_ancestors_within(
1271        &self,
1272        code_unit: &CodeUnit,
1273        scope: &DescendantIndexScope<'_>,
1274    ) -> Result<HierarchyAnswer, Cancelled> {
1275        query_within_scope(scope, || self.get_direct_ancestors(code_unit))
1276    }
1277
1278    /// [`Self::get_direct_descendants`] under a caller's deadline and workspace
1279    /// slice.
1280    ///
1281    /// `Incomplete` means required evidence was unavailable. `Cancelled` means
1282    /// the scope stopped. Neither is a complete empty answer; a failed build publishes
1283    /// nothing: a truncated index memoized as complete would be served to every
1284    /// later caller as the truth (the rule
1285    /// `cancelled_cold_candidate_discovery_does_not_publish_partial_index`
1286    /// pins for the Rust walk caches).
1287    ///
1288    /// The default checks the deadline once and delegates, which is the correct
1289    /// behaviour for a provider whose descendant answer is bounded by
1290    /// construction. Every provider that inverts the ancestor relation over the
1291    /// whole workspace overrides this; a provider that also honours
1292    /// [`DescendantIndexScope::admits`] builds one index per
1293    /// [`DescendantIndexVariant`]. Ignoring `admits` is sound -- the index is
1294    /// then a superset and the caller's own file filter still applies -- so
1295    /// only the providers where the prune pays for itself implement it.
1296    fn get_direct_descendants_within(
1297        &self,
1298        code_unit: &CodeUnit,
1299        scope: &DescendantIndexScope<'_>,
1300    ) -> Result<HierarchyAnswer, Cancelled> {
1301        query_within_scope(scope, || self.get_direct_descendants(code_unit))
1302    }
1303
1304    /// [`Self::get_descendants`] under a caller's deadline and workspace slice,
1305    /// polling once per node of the walk. Failures carry the same meaning as in
1306    /// [`Self::get_direct_descendants_within`].
1307    fn get_descendants_within(
1308        &self,
1309        code_unit: &CodeUnit,
1310        scope: &DescendantIndexScope<'_>,
1311    ) -> Result<HierarchyAnswer, Cancelled> {
1312        let mut result = None;
1313        self.with_hierarchy_query_for(code_unit, &mut |query| {
1314            result = Some(traverse_hierarchy_while(
1315                code_unit,
1316                query,
1317                scope.cancellation(),
1318                |query, next| query.direct_descendants_within(next, scope),
1319            ));
1320        });
1321        let mut answer = result.expect("hierarchy query callback runs once")?;
1322        answer.edges.sort();
1323        Ok(answer)
1324    }
1325
1326    fn get_polymorphic_matches<T: CodeUnitIndex>(
1327        &self,
1328        target: &CodeUnit,
1329        analyzer: &T,
1330    ) -> HierarchyAnswer
1331    where
1332        Self: Sized,
1333    {
1334        if !target.is_function() {
1335            return HierarchyAnswer::complete(Vec::new());
1336        }
1337
1338        let Some(parent) = analyzer.parent_of(target) else {
1339            return HierarchyAnswer::complete(Vec::new());
1340        };
1341
1342        self.get_descendants(&parent)
1343    }
1344}
1345
1346/// Exact declaration identities plus compact ancestor-to-descendant rows.
1347///
1348/// `open_candidates` are the declarations whose own ancestor answer was
1349/// open (an unresolved or ambiguous base, or a stopped proof). Their definite
1350/// ancestors are rows like any other; the rest of their ancestry is unknown, so
1351/// any of them may also descend from any other type. A row is complete only
1352/// when no other declaration is an open candidate.
1353pub struct DirectDescendantIndex {
1354    nodes: Box<[CodeUnit]>,
1355    row_by_ancestor: HashMap<CodeUnit, u32>,
1356    descendants: CompactRows<u32>,
1357    /// Any language that produces open candidates must include them in its
1358    /// descendants authority digest (for Python, `descendants_authority_digest`
1359    /// in python/mod.rs); otherwise two indexes that differ only in their open
1360    /// set would certify the same descendant answers.
1361    open_candidates: Box<[CodeUnit]>,
1362}
1363
1364impl DirectDescendantIndex {
1365    pub fn estimated_retained_bytes(&self) -> usize {
1366        let node_bytes = self
1367            .nodes
1368            .iter()
1369            .map(|unit| {
1370                std::mem::size_of::<CodeUnit>()
1371                    + unit.fq_name().len()
1372                    + unit.signature().map_or(0, str::len)
1373                    + unit.source().rel_path().as_os_str().len()
1374                    + unit.source().root().as_os_str().len()
1375            })
1376            .sum::<usize>();
1377        std::mem::size_of::<Self>()
1378            + node_bytes * 2
1379            + self.row_by_ancestor.capacity()
1380                * (std::mem::size_of::<CodeUnit>() + std::mem::size_of::<u32>() + 1)
1381            + self.descendants.estimated_bytes() as usize
1382            + self
1383                .open_candidates
1384                .iter()
1385                .map(|unit| std::mem::size_of::<CodeUnit>() + unit.fq_name().len())
1386                .sum::<usize>()
1387    }
1388
1389    pub fn from_indexed_nodes(
1390        nodes: Vec<CodeUnit>,
1391        index_by_node: HashMap<CodeUnit, u32>,
1392        mut edges: Vec<(u32, u32)>,
1393    ) -> Self {
1394        normalize_indexed_edges(&nodes, &index_by_node, &mut edges);
1395
1396        let row_count = usize::from(!edges.is_empty())
1397            + edges
1398                .windows(2)
1399                .filter(|pair| pair[0].0 != pair[1].0)
1400                .count();
1401        let mut row_by_ancestor = HashMap::default();
1402        let mut descendants = CompactRowsBuilder::with_capacity(row_count, edges.len());
1403        let mut cursor = 0;
1404        while cursor < edges.len() {
1405            let ancestor = edges[cursor].0;
1406            let start = cursor;
1407            while cursor < edges.len() && edges[cursor].0 == ancestor {
1408                cursor += 1;
1409            }
1410            let row =
1411                u32::try_from(descendants.rows()).expect("hierarchy index rows must fit in a u32");
1412            row_by_ancestor.insert(nodes[ancestor as usize].clone(), row);
1413            descendants.push_row(
1414                edges[start..cursor]
1415                    .iter()
1416                    .map(|(_, descendant)| *descendant),
1417            );
1418        }
1419        Self {
1420            nodes: nodes.into_boxed_slice(),
1421            row_by_ancestor,
1422            descendants: descendants.finish(),
1423            open_candidates: Box::default(),
1424        }
1425    }
1426
1427    /// Record the candidates whose ancestor answer is open, in `CodeUnit` order.
1428    pub fn with_open_candidates(mut self, mut open_candidates: Vec<CodeUnit>) -> Self {
1429        open_candidates.sort();
1430        open_candidates.dedup();
1431        self.open_candidates = open_candidates.into_boxed_slice();
1432        self
1433    }
1434
1435    /// The candidates whose ancestor answer is open, in `CodeUnit` order.
1436    pub fn open_candidates(&self) -> &[CodeUnit] {
1437        &self.open_candidates
1438    }
1439
1440    /// The definite descendants of `ancestor`, sorted, with the index's open
1441    /// candidates as typed incompleteness, excluding the ancestor itself.
1442    pub fn answer(&self, ancestor: &CodeUnit) -> HierarchyAnswer {
1443        let mut edges: Vec<_> = self.descendants(ancestor).into_iter().collect();
1444        edges.sort();
1445        let mut answer = HierarchyAnswer::complete(edges);
1446        let open_candidates: Vec<_> = self
1447            .open_candidates
1448            .iter()
1449            .filter(|candidate| *candidate != ancestor)
1450            .cloned()
1451            .collect();
1452        if !open_candidates.is_empty() {
1453            answer
1454                .open
1455                .push(HierarchyOpenReason::OpenAncestorCandidates(open_candidates));
1456        }
1457        answer
1458    }
1459
1460    pub fn descendants(&self, ancestor: &CodeUnit) -> HashSet<CodeUnit> {
1461        let Some(row) = self.row_by_ancestor.get(ancestor).copied() else {
1462            return HashSet::default();
1463        };
1464        self.descendants
1465            .row(row as usize)
1466            .iter()
1467            .map(|descendant| self.nodes[*descendant as usize].clone())
1468            .collect()
1469    }
1470}
1471
1472/// Invert the ancestor relation over every class the analyzer indexes.
1473///
1474/// `scope` decides two things. Its predicate drops declarations before they are
1475/// ever handed to `get_direct_ancestors`, which is where the per-declaration
1476/// resolution cost is charged (for C++ that is a whole transitive `#include`
1477/// closure per declaring file). Its token bounds the loop: `None` means the
1478/// build stopped short (including an unavailable source exclusion) and must not
1479/// be published.
1480pub fn build_direct_descendant_index<A, P>(
1481    analyzer: &A,
1482    provider: &P,
1483    scope: &DescendantIndexScope<'_>,
1484) -> Option<DirectDescendantIndex>
1485where
1486    A: CodeUnitIndex,
1487    P: TypeHierarchyProvider + ?Sized,
1488{
1489    let mut result = None;
1490    provider.with_hierarchy_query(&mut |query| {
1491        result = Some(build_direct_descendant_index_in_query(
1492            analyzer, query, scope,
1493        ));
1494    });
1495    result.expect("hierarchy query callback runs once")
1496}
1497
1498/// Invert ancestors inside an already-open query without opening another one.
1499pub fn build_direct_descendant_index_in_query<A: CodeUnitIndex>(
1500    analyzer: &A,
1501    query: &mut dyn HierarchyQuery,
1502    scope: &DescendantIndexScope<'_>,
1503) -> Option<DirectDescendantIndex> {
1504    let mut candidates = Vec::new();
1505    for candidate in analyzer.all_declarations().filter(CodeUnit::is_class) {
1506        if match scope.admits(&candidate) {
1507            Ok(value) => value,
1508            Err(reason) => {
1509                let _unavailable = reason;
1510                return None;
1511            }
1512        } {
1513            candidates.push(candidate);
1514        }
1515    }
1516    build_direct_descendant_index_from_candidates(
1517        candidates,
1518        |candidate| query.direct_ancestors_within(candidate, scope).ok(),
1519        &scope.keep_going(),
1520    )
1521}
1522
1523/// The edge-building half of [`build_direct_descendant_index`], for providers
1524/// that assemble their candidate list some other way.
1525///
1526/// `keep_going` is polled once per candidate. That granularity is the natural
1527/// checkpoint: one candidate is one `direct_ancestors` call, which is the unit
1528/// of work whose tens of thousands of repetitions made this loop unbounded in
1529/// the first place (issue #1748). `direct_ancestors` answers `None` when its
1530/// own work stopped short. A stopped answer contributes its proven edges and
1531/// remains an unbounded open candidate. Its caller retains the stop receipt
1532/// and decides whether the index can be memoized. An open answer contributes
1533/// its definite edges and makes the candidate an open candidate of the index,
1534/// unless its only open reasons name types outside the index
1535/// ([`HierarchyAnswer::keeps_indexed_edges_exact`]).
1536pub fn build_direct_descendant_index_from_candidates<F>(
1537    mut candidates: Vec<CodeUnit>,
1538    mut direct_ancestors: F,
1539    keep_going: &dyn Fn() -> bool,
1540) -> Option<DirectDescendantIndex>
1541where
1542    F: FnMut(&CodeUnit) -> Option<HierarchyAnswer>,
1543{
1544    candidates.sort();
1545    candidates.dedup();
1546    let mut types_by_fq_name: HashMap<String, Vec<CodeUnit>> = HashMap::default();
1547    for candidate in &candidates {
1548        types_by_fq_name
1549            .entry(candidate.fq_name())
1550            .or_default()
1551            .push(candidate.clone());
1552    }
1553    let mut nodes = candidates.clone();
1554    let mut index_by_node: HashMap<_, _> = nodes
1555        .iter()
1556        .enumerate()
1557        .map(|(index, node)| {
1558            (
1559                node.clone(),
1560                u32::try_from(index).expect("hierarchy index declarations must fit in a u32"),
1561            )
1562        })
1563        .collect();
1564    let mut edges = Vec::new();
1565    let mut open_candidates = Vec::new();
1566    for candidate in candidates {
1567        if !keep_going() {
1568            return None;
1569        }
1570        let descendant = index_by_node[&candidate];
1571        let answer = direct_ancestors(&candidate)?;
1572        // A clause naming a type outside the index leaves every indexed edge
1573        // known: no indexed type can descend through it, so it does not make
1574        // the candidate open (#7363).
1575        if !answer.keeps_indexed_edges_exact() {
1576            open_candidates.push(candidate.clone());
1577        }
1578        for ancestor in answer.edges {
1579            let ancestor = types_by_fq_name
1580                .get(&ancestor.fq_name())
1581                .and_then(|same_name| {
1582                    let mut same_source = same_name
1583                        .iter()
1584                        .filter(|unit| unit.source() == candidate.source());
1585                    let exact = same_source.next()?;
1586                    same_source.next().is_none().then(|| exact.clone())
1587                })
1588                .unwrap_or(ancestor);
1589            let ancestor = *index_by_node.entry(ancestor.clone()).or_insert_with(|| {
1590                let index = u32::try_from(nodes.len())
1591                    .expect("hierarchy index declarations must fit in a u32");
1592                nodes.push(ancestor);
1593                index
1594            });
1595            edges.push((ancestor, descendant));
1596        }
1597    }
1598    Some(
1599        DirectDescendantIndex::from_indexed_nodes(nodes, index_by_node, edges)
1600            .with_open_candidates(open_candidates),
1601    )
1602}
1603
1604fn traverse_hierarchy(
1605    root: &CodeUnit,
1606    query: &mut dyn HierarchyQuery,
1607    mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> HierarchyAnswer,
1608) -> HierarchyAnswer {
1609    traverse_hierarchy_edges(root, |unit| next(query, unit))
1610}
1611
1612fn traverse_hierarchy_while(
1613    root: &CodeUnit,
1614    query: &mut dyn HierarchyQuery,
1615    cancellation: &CancellationToken,
1616    mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1617) -> Result<HierarchyAnswer, Cancelled> {
1618    traverse_hierarchy_edges_while(root, cancellation, |unit| next(query, unit))
1619}
1620
1621/// [`traverse_hierarchy`] under a deadline: polls once per node popped and
1622/// propagates a stopped step as `Err(Cancelled)` rather than returning the nodes it had
1623/// already collected. A partial subtype set read as complete would let a caller
1624/// conclude that a class has no further subclasses.
1625fn traverse_hierarchy_edges_while<F>(
1626    root: &CodeUnit,
1627    cancellation: &CancellationToken,
1628    mut next: F,
1629) -> Result<HierarchyAnswer, Cancelled>
1630where
1631    F: FnMut(&CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1632{
1633    let mut result = HierarchyAnswer::complete(Vec::new());
1634    let mut seen = BTreeSet::new();
1635    let mut queue = VecDeque::from([root.clone()]);
1636    while let Some(current) = queue.pop_front() {
1637        let answer = next(&current)?;
1638        result.ambiguous.extend(answer.ambiguous);
1639        for reason in answer.open {
1640            // One index's open candidates are the same at every node of the
1641            // walk; name each distinct set once.
1642            if let HierarchyOpenReason::OpenAncestorCandidates(candidates) = &reason
1643                && result.open.iter().any(|seen| {
1644                    matches!(seen, HierarchyOpenReason::OpenAncestorCandidates(other) if other == candidates)
1645                })
1646            {
1647                continue;
1648            }
1649            result.open.push(reason);
1650        }
1651        for item in answer.edges {
1652            if seen.insert(item.fq_name()) {
1653                queue.push_back(item.clone());
1654                result.edges.push(item);
1655            }
1656        }
1657        if !queue.is_empty() && cancellation.is_cancelled() {
1658            return Err(Cancelled);
1659        }
1660    }
1661    Ok(result)
1662}
1663
1664fn traverse_hierarchy_edges<F>(root: &CodeUnit, mut next: F) -> HierarchyAnswer
1665where
1666    F: FnMut(&CodeUnit) -> HierarchyAnswer,
1667{
1668    // Both variants share the traversal and completeness accounting. An owned
1669    // live token makes stopping impossible for this unscoped request.
1670    traverse_hierarchy_edges_while(root, &CancellationToken::new(), |unit| Ok(next(unit)))
1671        .expect("unscoped hierarchy traversal cannot stop")
1672}
1673
1674#[cfg(test)]
1675mod hierarchy_traversal_properties {
1676    use super::*;
1677    use crate::analyzer::model::CodeUnitType;
1678    use proptest::prelude::*;
1679    use std::collections::BTreeMap;
1680
1681    const NODES: usize = 8;
1682
1683    fn node(index: usize) -> CodeUnit {
1684        CodeUnit::new(
1685            ProjectFile::new(std::env::temp_dir(), "Hierarchy.java"),
1686            CodeUnitType::Class,
1687            "",
1688            format!("N{index}"),
1689        )
1690    }
1691
1692    #[test]
1693    fn transitive_walks_borrow_one_query_and_preserve_scoped_dispatch() {
1694        use std::sync::atomic::{AtomicUsize, Ordering};
1695        struct Provider(AtomicUsize);
1696        struct Query;
1697        impl HierarchyQuery for Query {
1698            fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1699                let index = index_of(unit);
1700                HierarchyAnswer::complete(if index < 2 {
1701                    vec![node(index + 1)]
1702                } else {
1703                    Vec::new()
1704                })
1705            }
1706            fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1707                self.direct_ancestors(unit)
1708            }
1709            fn member_family_ancestors(&mut self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1710                MemberFamilyAncestors::default()
1711            }
1712            fn direct_descendants_within(
1713                &mut self,
1714                _unit: &CodeUnit,
1715                _scope: &DescendantIndexScope<'_>,
1716            ) -> Result<HierarchyAnswer, Cancelled> {
1717                Err(Cancelled)
1718            }
1719        }
1720        impl TypeHierarchyProvider for Provider {
1721            fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1722                panic!("the walk must use its query")
1723            }
1724            fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1725                panic!("the walk must use its query")
1726            }
1727            fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1728                self.0.fetch_add(1, Ordering::Relaxed);
1729                run(&mut Query);
1730            }
1731        }
1732        let provider = Provider(AtomicUsize::new(0));
1733        assert_eq!(
1734            provider.get_ancestors(&node(0)).edges,
1735            vec![node(1), node(2)]
1736        );
1737        assert_eq!(provider.0.load(Ordering::Relaxed), 1);
1738        assert_eq!(
1739            provider.get_descendants(&node(0)).edges,
1740            vec![node(1), node(2)]
1741        );
1742        assert_eq!(provider.0.load(Ordering::Relaxed), 2);
1743        let cancellation = CancellationToken::new();
1744        assert!(
1745            provider
1746                .get_descendants_within(
1747                    &node(0),
1748                    &DescendantIndexScope::whole_workspace(&cancellation)
1749                )
1750                .is_err()
1751        );
1752        assert_eq!(provider.0.load(Ordering::Relaxed), 3);
1753    }
1754
1755    #[test]
1756    fn default_query_forwards_scoped_provider_overrides() {
1757        struct Provider;
1758        impl TypeHierarchyProvider for Provider {
1759            fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1760                HierarchyAnswer::complete(vec![node(1)])
1761            }
1762            fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1763                HierarchyAnswer::complete(vec![node(2)])
1764            }
1765            fn get_direct_ancestors_within(
1766                &self,
1767                _unit: &CodeUnit,
1768                _scope: &DescendantIndexScope<'_>,
1769            ) -> Result<HierarchyAnswer, Cancelled> {
1770                Err(Cancelled)
1771            }
1772            fn member_family_ancestors(&self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1773                MemberFamilyAncestors {
1774                    resolved: vec![node(3)],
1775                    ..Default::default()
1776                }
1777            }
1778        }
1779        let cancellation = CancellationToken::new();
1780        Provider.with_hierarchy_query(&mut |query| {
1781            assert_eq!(query.direct_ancestors(&node(0)).edges, vec![node(1)]);
1782            assert_eq!(query.direct_descendants(&node(0)).edges, vec![node(2)]);
1783            assert_eq!(
1784                query.member_family_ancestors(&node(0)).resolved,
1785                vec![node(3)]
1786            );
1787            assert!(
1788                query
1789                    .direct_ancestors_within(
1790                        &node(0),
1791                        &DescendantIndexScope::whole_workspace(&cancellation)
1792                    )
1793                    .is_err()
1794            );
1795        });
1796    }
1797
1798    fn index_of(unit: &CodeUnit) -> usize {
1799        unit.fq_name()[1..].parse().expect("test node name")
1800    }
1801
1802    #[test]
1803    fn closure_preserves_uncertainty_without_traversing_alternatives() {
1804        let mut visited = Vec::new();
1805        let answer = traverse_hierarchy_edges(&node(0), |unit| {
1806            let id = index_of(unit);
1807            visited.push(id);
1808            match id {
1809                0 => HierarchyAnswer {
1810                    edges: vec![node(1), node(1)],
1811                    ambiguous: vec![vec![node(2), node(3)]],
1812                    open: Vec::new(),
1813                },
1814                1 => HierarchyAnswer {
1815                    edges: Vec::new(),
1816                    ambiguous: vec![vec![node(4), node(5)]],
1817                    open: vec![HierarchyOpenReason::UnreadAncestor(
1818                        UnreadMemberFamilyAncestor {
1819                            name: "External".into(),
1820                            inventory: None,
1821                        },
1822                    )],
1823                },
1824                _ => panic!("ambiguous alternatives must not be traversed"),
1825            }
1826        });
1827        assert_eq!(visited, vec![0, 1]);
1828        assert_eq!(answer.edges, vec![node(1)]);
1829        assert_eq!(
1830            answer.ambiguous,
1831            vec![vec![node(2), node(3)], vec![node(4), node(5)]]
1832        );
1833        assert!(
1834            matches!(answer.open.as_slice(), [HierarchyOpenReason::UnreadAncestor(ancestor)] if ancestor.name == "External")
1835        );
1836        assert!(!answer.is_complete());
1837    }
1838
1839    #[test]
1840    #[brokk_bifrost_test_macros::hardwon(
1841        "#12211: an open candidate tainted its own descendant answer"
1842    )]
1843    #[brokk_bifrost_test_macros::hardwon(
1844        "#12172: an open candidate's own ancestry tainted its descendant query"
1845    )]
1846    fn an_open_candidate_does_not_taint_its_own_descendants() {
1847        let project = ProjectFile::new(std::env::temp_dir(), "Hierarchy.java");
1848        let class = |name: &str| CodeUnit::new(project.clone(), CodeUnitType::Class, "", name);
1849        let base = class("Base");
1850        let open = class("Open");
1851        let derived = class("Derived");
1852        let index = build_direct_descendant_index_from_candidates(
1853            vec![base.clone(), open.clone(), derived.clone()],
1854            |candidate| {
1855                if candidate == &open {
1856                    Some(HierarchyAnswer {
1857                        edges: vec![base.clone()],
1858                        open: vec![HierarchyOpenReason::UnreadAncestor(
1859                            UnreadMemberFamilyAncestor {
1860                                name: "Mystery".into(),
1861                                inventory: None,
1862                            },
1863                        )],
1864                        ambiguous: Vec::new(),
1865                    })
1866                } else if candidate == &derived {
1867                    Some(HierarchyAnswer::complete(vec![open.clone()]))
1868                } else {
1869                    Some(HierarchyAnswer::complete(Vec::new()))
1870                }
1871            },
1872            &|| true,
1873        )
1874        .expect("finished open answers build an index");
1875
1876        let base_answer = index.answer(&base);
1877        assert!(!base_answer.is_complete());
1878        assert!(matches!(
1879            base_answer.open.as_slice(),
1880            [HierarchyOpenReason::OpenAncestorCandidates(candidates)]
1881                if candidates == std::slice::from_ref(&open)
1882        ));
1883
1884        let own = index.answer(&open);
1885        assert!(own.is_complete(), "{own:?}");
1886        assert_eq!(own.edges, vec![derived]);
1887    }
1888
1889    /// Edge lists may repeat a target, hold self loops and form cycles.
1890    fn graphs() -> impl Strategy<Value = Vec<Vec<usize>>> {
1891        proptest::collection::vec(proptest::collection::vec(0..NODES, 0..5), NODES)
1892    }
1893
1894    /// Reference by relaxation: `distance[n]` is the fewest edges on a path
1895    /// from `root` to `n` that uses at least one edge. This makes the root
1896    /// reachable only through a cycle, which is what the traversal reports.
1897    fn reference_distances(graph: &[Vec<usize>], root: usize) -> BTreeMap<usize, usize> {
1898        let mut distance: BTreeMap<usize, usize> = BTreeMap::new();
1899        for &next in &graph[root] {
1900            distance.insert(next, 1);
1901        }
1902        loop {
1903            let mut changed = false;
1904            for (from, edges) in graph.iter().enumerate() {
1905                let Some(&base) = distance.get(&from) else {
1906                    continue;
1907                };
1908                for &to in edges {
1909                    if distance.get(&to).is_none_or(|&known| known > base + 1) {
1910                        distance.insert(to, base + 1);
1911                        changed = true;
1912                    }
1913                }
1914            }
1915            if !changed {
1916                return distance;
1917            }
1918        }
1919    }
1920
1921    proptest! {
1922        #![proptest_config(ProptestConfig::with_cases(128))]
1923
1924        /// On any graph, cyclic or not, the traversal terminates, returns each
1925        /// reachable declaration exactly once in breadth-first order, and asks
1926        /// for each declaration's neighbours once (the root twice when a cycle
1927        /// returns to it).
1928        #[test]
1929        fn visits_exactly_the_reachable_set_once_in_breadth_first_order(
1930            graph in graphs(),
1931            root in 0..NODES,
1932        ) {
1933            let mut calls: BTreeMap<usize, usize> = BTreeMap::new();
1934            let result = traverse_hierarchy_edges(&node(root), |unit| {
1935                let id = index_of(unit);
1936                *calls.entry(id).or_default() += 1;
1937                HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())
1938            });
1939            let found: Vec<usize> = result.edges.iter().map(index_of).collect();
1940
1941            let distance = reference_distances(&graph, root);
1942            let unique: BTreeSet<usize> = found.iter().copied().collect();
1943            prop_assert_eq!(found.len(), unique.len(), "a declaration was returned twice: {:?}", found);
1944            prop_assert_eq!(unique, distance.keys().copied().collect::<BTreeSet<_>>());
1945            prop_assert!(
1946                found.windows(2).all(|pair| distance[&pair[0]] <= distance[&pair[1]]),
1947                "not breadth-first: {:?} with distances {:?}", found, distance
1948            );
1949            // The root is not in the seen set when the walk starts, so a cycle
1950            // back to it expands it a second time; every other node once.
1951            prop_assert!(
1952                calls.iter().all(|(&id, &count)| count == 1 || (id == root && count == 2)),
1953                "repeated expansion: {:?}", calls
1954            );
1955
1956            // The deadline-aware variant agrees when never cancelled.
1957            let live = CancellationToken::new();
1958            let guarded = traverse_hierarchy_edges_while(&node(root), &live, |unit| {
1959                Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1960            });
1961            let guarded = guarded.expect("live traversal");
1962            prop_assert!(guarded.is_complete());
1963            prop_assert_eq!(guarded.edges, result.edges);
1964        }
1965
1966        /// A failed neighbour step is propagated, not hidden behind a partial
1967        /// answer; a cancelled token stops a traversal that has work left but
1968        /// does not disturb one whose root has no neighbours.
1969        #[test]
1970        fn guarded_traversal_never_returns_a_partial_answer(
1971            graph in graphs(),
1972            root in 0..NODES,
1973            fail_on in 0..NODES,
1974        ) {
1975            let reachable = reference_distances(&graph, root);
1976            let failing = traverse_hierarchy_edges_while(&node(root), &CancellationToken::new(), |unit| {
1977                let id = index_of(unit);
1978                if id == fail_on { Err(Cancelled) } else { Ok(HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())) }
1979            });
1980            // The failing node's neighbours are requested when it is the root or
1981            // is itself returned, so it is only skipped when neither holds.
1982            let requested = fail_on == root || reachable.contains_key(&fail_on);
1983            prop_assert_eq!(failing.is_err(), requested);
1984
1985            let cancelled = CancellationToken::new();
1986            cancelled.cancel();
1987            let stopped = traverse_hierarchy_edges_while(&node(root), &cancelled, |unit| {
1988                Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1989            });
1990            prop_assert_eq!(stopped.is_err(), !graph[root].is_empty());
1991            if graph[root].is_empty() {
1992                let stopped = stopped.expect("empty traversal");
1993                prop_assert!(stopped.is_complete());
1994                prop_assert!(stopped.edges.is_empty());
1995            }
1996        }
1997    }
1998}