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/// One declared parameter type of a nominal-family member, resolved and
819/// erased (JLS 4.6) from the declaration's own type node.
820///
821/// Override matching compares these per position (JLS 8.4.2, 8.4.8.1). A type
822/// variable of the member's *owner* keeps its index, because a subtype that
823/// names the owner with type arguments substitutes them before erasure
824/// (`compareTo(T)` in `Comparable<Box>` is `compareTo(Box)`). Any other type
825/// variable is replaced by the erasure of its leftmost bound.
826#[derive(Debug, Clone, PartialEq, Eq)]
827pub enum MemberFamilyParameterType {
828    /// A primitive type, by keyword.
829    Primitive(String),
830    /// A nominal type whose fully qualified name is known.
831    Nominal(String),
832    /// A nominal type whose identity the analyzer could not establish. It
833    /// carries every fully qualified name the language's name tiers could give
834    /// the spelling at its use site, strongest first, and the type is one of
835    /// them. Two equal lists are the same type, because the tiers pick from a
836    /// list by a rule of its inputs; two disjoint lists are different types.
837    /// An empty list is a type that could not be read at all.
838    Unresolved(Vec<String>),
839    Array(Box<MemberFamilyParameterType>),
840    /// The owner's type parameter at `index`, with the erasure of its bound.
841    OwnerTypeParameter {
842        index: usize,
843        erasure: Box<MemberFamilyParameterType>,
844    },
845}
846
847/// The type arguments a subtype's declaration passes to one direct supertype,
848/// each as a [`MemberFamilyParameterType`] in the subtype's scope.
849#[derive(Debug, Clone, PartialEq, Eq)]
850pub enum MemberFamilySupertypeArguments {
851    /// The supertype is named raw (or is not generic): its members are erased.
852    Raw,
853    Arguments(Vec<MemberFamilyParameterType>),
854    /// The clause naming the supertype could not be read or singled out.
855    Unknown,
856}
857
858/// An ancestor whose member declarations the workspace did not read.
859#[derive(Debug, Clone, PartialEq, Eq)]
860pub struct UnreadMemberFamilyAncestor {
861    pub name: String,
862    pub inventory: Option<&'static [PlatformInventoryMethod]>,
863}
864
865#[derive(Debug, Default)]
866pub struct MemberFamilyAncestors {
867    pub resolved: Vec<CodeUnit>,
868    pub ambiguous: Vec<Vec<CodeUnit>>,
869    pub unread: Vec<UnreadMemberFamilyAncestor>,
870}
871
872/// Evidence that a hierarchy query could not close its search boundary.
873#[derive(Debug, Clone, PartialEq, Eq)]
874pub enum HierarchyOpenReason {
875    /// Existing hierarchy diagnostics, including `HierarchyTruncated` and
876    /// `AncestorExternalUnindexed`, retain their consumer-side vocabulary.
877    MemberFamily(crate::analyzer::structural::resolution::MemberFamilyReason),
878    /// The descendant index could not acquire the evidence needed to fill.
879    DescendantIndexUnavailable,
880    /// Forward structural-satisfaction coverage (interfaces a type satisfies
881    /// without embedding them) is not closed.
882    ForwardSatisfactionIncomplete,
883    /// Preserve the unread name and any language-specified member inventory.
884    UnreadAncestor(UnreadMemberFamilyAncestor),
885    /// A descendant index was built, but these candidates' own ancestor
886    /// answers are open: any of them may be a descendant of the queried type
887    /// through an ancestor the language could not close. The definite edges
888    /// beside this reason are still correct.
889    OpenAncestorCandidates(Vec<CodeUnit>),
890    /// A supertype clause of `declared_by` names `name`, and the language's
891    /// type lookup finds no indexed declaration for it: a library type read
892    /// from an assembly, for example. When `may_name_indexed` is false the
893    /// language proved the clause names a type outside the index, so the
894    /// definite edges still name every indexed ancestor; when it is true the
895    /// lookup failure proves nothing about indexed types.
896    ExternalUnindexedAncestor {
897        name: String,
898        declared_by: CodeUnit,
899        may_name_indexed: bool,
900    },
901    /// Source could not establish the supertype clauses of `declared_by`, so
902    /// the definite edges may omit any ancestor.
903    SupertypesUnread { declared_by: CodeUnit },
904}
905
906impl HierarchyOpenReason {
907    /// Stable reason label with the boundary name retained as data.
908    pub fn description(&self) -> String {
909        match self {
910            Self::UnreadAncestor(ancestor) => format!("{}: {}", self.as_str(), ancestor.name),
911            Self::OpenAncestorCandidates(candidates) => {
912                let names: Vec<String> = candidates.iter().map(CodeUnit::fq_name).collect();
913                format!("{}: {}", self.as_str(), names.join(", "))
914            }
915            Self::ExternalUnindexedAncestor { name, .. } => format!("{}: {name}", self.as_str()),
916            _ => self.as_str().to_string(),
917        }
918    }
919
920    /// Whether the work behind this reason stopped short, as opposed to
921    /// finishing with a closed-world gap. An index builder keeps its positive
922    /// edges and treats the declaration as an unbounded open candidate; the
923    /// caller retains the stop receipt and decides whether to memoize it.
924    pub fn stopped_short(&self) -> bool {
925        matches!(
926            self,
927            Self::DescendantIndexUnavailable
928                | Self::MemberFamily(
929                    crate::analyzer::structural::resolution::MemberFamilyReason::HierarchyTruncated
930                        | crate::analyzer::structural::resolution::MemberFamilyReason::ProviderUnavailable
931                )
932        )
933    }
934
935    /// Stable public reason label, shared by hierarchy presentation surfaces.
936    pub fn as_str(&self) -> &'static str {
937        match self {
938            Self::MemberFamily(reason) => reason.label(),
939            Self::DescendantIndexUnavailable => "descendant_index_unavailable",
940            Self::ForwardSatisfactionIncomplete => "forward_satisfaction_incomplete",
941            Self::UnreadAncestor(_) => "unread_ancestor",
942            Self::OpenAncestorCandidates(_) => "open_ancestor_candidates",
943            Self::ExternalUnindexedAncestor { .. } => {
944                crate::analyzer::structural::resolution::MemberFamilyReason::AncestorExternalUnindexed
945                    .label()
946            }
947            Self::SupertypesUnread { .. } => "supertypes_unread",
948        }
949    }
950
951    /// The declaration whose supertype clauses left the answer open, when the
952    /// reason names one.
953    pub fn declared_by(&self) -> Option<&CodeUnit> {
954        match self {
955            Self::ExternalUnindexedAncestor { declared_by, .. }
956            | Self::SupertypesUnread { declared_by } => Some(declared_by),
957            _ => None,
958        }
959    }
960
961    /// Whether the definite edges still name every indexed ancestor, so the
962    /// inverse (descendant) relation over indexed types built from them is
963    /// exact. Only a clause proven to name a type outside the index
964    /// qualifies.
965    pub fn keeps_indexed_edges_exact(&self) -> bool {
966        matches!(
967            self,
968            Self::ExternalUnindexedAncestor {
969                may_name_indexed: false,
970                ..
971            }
972        )
973    }
974}
975
976/// A hierarchy answer owned by one request. Never retain it in a memo or cache.
977///
978/// Only `edges` are definite. Each ambiguous group contains alternatives for
979/// one unresolved edge; none of those alternatives is a definite ancestor or
980/// descendant. Ambiguity and open reasons both prevent an exhaustive answer.
981#[derive(Debug, Clone, PartialEq, Eq)]
982pub struct HierarchyAnswer<T = CodeUnit> {
983    pub edges: Vec<T>,
984    pub ambiguous: Vec<Vec<T>>,
985    pub open: Vec<HierarchyOpenReason>,
986}
987
988impl<T> HierarchyAnswer<T> {
989    /// Construct a complete answer, preserving the provider's edge order.
990    pub fn complete(edges: Vec<T>) -> Self {
991        Self {
992            edges,
993            ambiguous: Vec::new(),
994            open: Vec::new(),
995        }
996    }
997
998    /// Unavailable facts must name their gap explicitly.
999    pub fn incomplete(reason: HierarchyOpenReason) -> Self {
1000        Self {
1001            edges: Vec::new(),
1002            ambiguous: Vec::new(),
1003            open: vec![reason],
1004        }
1005    }
1006
1007    /// Union definite edges in CodeUnit order while retaining all uncertainty.
1008    pub fn merge(&mut self, other: Self)
1009    where
1010        T: Ord,
1011    {
1012        self.edges.extend(other.edges);
1013        self.edges.sort();
1014        self.edges.dedup();
1015        self.ambiguous.extend(other.ambiguous);
1016        self.open.extend(other.open);
1017    }
1018
1019    pub fn is_complete(&self) -> bool {
1020        self.ambiguous.is_empty() && self.open.is_empty()
1021    }
1022
1023    /// Whether the query stopped short (see [`HierarchyOpenReason::stopped_short`]).
1024    pub fn stopped_short(&self) -> bool {
1025        self.open.iter().any(HierarchyOpenReason::stopped_short)
1026    }
1027
1028    /// Whether the definite edges name every indexed ancestor, so an inverse
1029    /// (descendant) relation over indexed types built from them is exact. An
1030    /// answer whose only open reasons name types outside the index qualifies.
1031    pub fn keeps_indexed_edges_exact(&self) -> bool {
1032        self.ambiguous.is_empty()
1033            && self
1034                .open
1035                .iter()
1036                .all(HierarchyOpenReason::keeps_indexed_edges_exact)
1037    }
1038
1039    /// Lossy: drops ambiguous groups and open reasons. Only for callers whose
1040    /// language answers are complete by construction.
1041    pub fn definite(&self) -> &[T] {
1042        &self.edges
1043    }
1044}
1045
1046/// One caller-owned hierarchy session, borrowed by every step of a walk.
1047/// The handle has one borrower and is never shared between Rayon tasks.
1048pub trait HierarchyQuery {
1049    fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1050    fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer;
1051    fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors;
1052
1053    fn direct_ancestors_within(
1054        &mut self,
1055        unit: &CodeUnit,
1056        scope: &DescendantIndexScope<'_>,
1057    ) -> Result<HierarchyAnswer, Cancelled> {
1058        query_within_scope(scope, || self.direct_ancestors(unit))
1059    }
1060
1061    fn direct_descendants_within(
1062        &mut self,
1063        unit: &CodeUnit,
1064        scope: &DescendantIndexScope<'_>,
1065    ) -> Result<HierarchyAnswer, Cancelled> {
1066        query_within_scope(scope, || self.direct_descendants(unit))
1067    }
1068}
1069
1070/// Compatibility adapter for providers whose direct reads need no session.
1071/// Each method forwards to the original provider, including scoped overrides.
1072pub struct ForwardingHierarchyQuery<'a, P: ?Sized>(pub &'a P);
1073
1074impl<P: TypeHierarchyProvider + ?Sized> HierarchyQuery for ForwardingHierarchyQuery<'_, P> {
1075    fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1076        self.0.get_direct_ancestors(unit)
1077    }
1078    fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1079        self.0.get_direct_descendants(unit)
1080    }
1081    fn member_family_ancestors(&mut self, unit: &CodeUnit) -> MemberFamilyAncestors {
1082        self.0.member_family_ancestors(unit)
1083    }
1084    fn direct_ancestors_within(
1085        &mut self,
1086        unit: &CodeUnit,
1087        scope: &DescendantIndexScope<'_>,
1088    ) -> Result<HierarchyAnswer, Cancelled> {
1089        self.0.get_direct_ancestors_within(unit, scope)
1090    }
1091    fn direct_descendants_within(
1092        &mut self,
1093        unit: &CodeUnit,
1094        scope: &DescendantIndexScope<'_>,
1095    ) -> Result<HierarchyAnswer, Cancelled> {
1096        self.0.get_direct_descendants_within(unit, scope)
1097    }
1098}
1099
1100pub trait TypeHierarchyProvider: Send + Sync {
1101    /// Invoke the walk once with a request-local hierarchy handle.
1102    fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1103        run(&mut ForwardingHierarchyQuery(self));
1104    }
1105
1106    /// Root-aware entry lets workspace dispatch exclude unrelated delegates.
1107    /// Providers without workspace routing use their ordinary query boundary.
1108    fn with_hierarchy_query_for(
1109        &self,
1110        _root: &CodeUnit,
1111        run: &mut dyn FnMut(&mut dyn HierarchyQuery),
1112    ) {
1113        self.with_hierarchy_query(run);
1114    }
1115
1116    fn get_direct_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1117    fn get_direct_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer;
1118
1119    /// The nominal member walk also needs the ancestors not represented by
1120    /// workspace declarations. Languages opt in without changing type lookup.
1121    /// The default names each clause the provider reported as outside the
1122    /// index as an unread ancestor without an inventory, so a family that
1123    /// reaches it stays open under that ancestor's name (#7363).
1124    fn member_family_ancestors(&self, owner: &CodeUnit) -> MemberFamilyAncestors {
1125        let answer = self.get_direct_ancestors(owner);
1126        MemberFamilyAncestors {
1127            resolved: answer.edges,
1128            ambiguous: answer.ambiguous,
1129            unread: answer
1130                .open
1131                .into_iter()
1132                .filter_map(|reason| match reason {
1133                    HierarchyOpenReason::ExternalUnindexedAncestor { name, .. } => {
1134                        Some(UnreadMemberFamilyAncestor {
1135                            name,
1136                            inventory: None,
1137                        })
1138                    }
1139                    _ => None,
1140                })
1141                .collect(),
1142        }
1143    }
1144
1145    /// Whether an unread ancestor's complete method inventory can declare
1146    /// `member`. A method of another name never can. Parameter evidence from
1147    /// the language narrows further; without it the side stays open.
1148    fn member_family_inventory_matches(
1149        &self,
1150        member: &CodeUnit,
1151        inventory: &[PlatformInventoryMethod],
1152    ) -> bool {
1153        let methods: Vec<_> = inventory
1154            .iter()
1155            .filter(|method| method.name == member.identifier())
1156            .collect();
1157        if methods.is_empty() {
1158            return false;
1159        }
1160        let Some(arity) = self.member_family_parameter_arity(member) else {
1161            return true;
1162        };
1163        let methods: Vec<_> = methods
1164            .into_iter()
1165            .filter(|method| method.parameters.len() == arity)
1166            .collect();
1167        if methods.is_empty() {
1168            return false;
1169        }
1170        if methods.iter().any(|method| method.parameters.is_empty()) {
1171            return true;
1172        }
1173        let Some(parameters) = self.member_family_erased_parameters(member) else {
1174            return true;
1175        };
1176        methods.iter().any(|method| {
1177            parameters
1178                .iter()
1179                .map(String::as_str)
1180                .eq(method.parameters.iter().copied())
1181        })
1182    }
1183
1184    /// The member's declared parameter count, when the language knows it.
1185    fn member_family_parameter_arity(&self, _member: &CodeUnit) -> Option<usize> {
1186        None
1187    }
1188
1189    /// The member's parameter types resolved and erased the way the platform
1190    /// inventory spells them, when the language can resolve them.
1191    fn member_family_erased_parameters(&self, _member: &CodeUnit) -> Option<Vec<String>> {
1192        None
1193    }
1194
1195    /// The member's declared parameter types for override matching, or `None`
1196    /// when the language does not read them structurally. The shared walk then
1197    /// falls back to the recorded parameter spellings, which can confirm an
1198    /// override but never refute one.
1199    fn member_family_parameter_types(
1200        &self,
1201        _member: &CodeUnit,
1202    ) -> Option<Vec<MemberFamilyParameterType>> {
1203        None
1204    }
1205
1206    /// The type arguments `subtype` passes to its direct supertype `supertype`.
1207    fn member_family_supertype_arguments(
1208        &self,
1209        _subtype: &CodeUnit,
1210        _supertype: &CodeUnit,
1211    ) -> MemberFamilySupertypeArguments {
1212        MemberFamilySupertypeArguments::Unknown
1213    }
1214
1215    fn supports_type_hierarchy(&self, code_unit: &CodeUnit) -> bool {
1216        code_unit.is_class()
1217    }
1218
1219    fn get_ancestors(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1220        let mut result = None;
1221        self.with_hierarchy_query_for(code_unit, &mut |query| {
1222            result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1223                query.direct_ancestors(next)
1224            }));
1225        });
1226        result.expect("hierarchy query callback runs once")
1227    }
1228
1229    fn get_descendants(&self, code_unit: &CodeUnit) -> HierarchyAnswer {
1230        let mut result = None;
1231        self.with_hierarchy_query_for(code_unit, &mut |query| {
1232            result = Some(traverse_hierarchy(code_unit, query, |query, next| {
1233                query.direct_descendants(next)
1234            }));
1235        });
1236        let mut answer = result.expect("hierarchy query callback runs once");
1237        answer.edges.sort();
1238        answer
1239    }
1240
1241    /// [`Self::get_direct_ancestors`] under a caller's deadline.
1242    ///
1243    /// `Err(Cancelled)` means the resolution stopped short; it is never an empty answer,
1244    /// which stays the honest way to say "no resolvable base types". The
1245    /// default checks the deadline once and delegates, which is right for a
1246    /// provider whose ancestor resolution is a lookup. C++ overrides it because
1247    /// resolving one class's bases means walking that file's whole transitive
1248    /// `#include` closure.
1249    fn get_direct_ancestors_within(
1250        &self,
1251        code_unit: &CodeUnit,
1252        scope: &DescendantIndexScope<'_>,
1253    ) -> Result<HierarchyAnswer, Cancelled> {
1254        query_within_scope(scope, || self.get_direct_ancestors(code_unit))
1255    }
1256
1257    /// [`Self::get_direct_descendants`] under a caller's deadline and workspace
1258    /// slice.
1259    ///
1260    /// `Incomplete` means required evidence was unavailable. `Cancelled` means
1261    /// the scope stopped. Neither is a complete empty answer; a failed build publishes
1262    /// nothing: a truncated index memoized as complete would be served to every
1263    /// later caller as the truth (the rule
1264    /// `cancelled_cold_candidate_discovery_does_not_publish_partial_index`
1265    /// pins for the Rust walk caches).
1266    ///
1267    /// The default checks the deadline once and delegates, which is the correct
1268    /// behaviour for a provider whose descendant answer is bounded by
1269    /// construction. Every provider that inverts the ancestor relation over the
1270    /// whole workspace overrides this; a provider that also honours
1271    /// [`DescendantIndexScope::admits`] builds one index per
1272    /// [`DescendantIndexVariant`]. Ignoring `admits` is sound -- the index is
1273    /// then a superset and the caller's own file filter still applies -- so
1274    /// only the providers where the prune pays for itself implement it.
1275    fn get_direct_descendants_within(
1276        &self,
1277        code_unit: &CodeUnit,
1278        scope: &DescendantIndexScope<'_>,
1279    ) -> Result<HierarchyAnswer, Cancelled> {
1280        query_within_scope(scope, || self.get_direct_descendants(code_unit))
1281    }
1282
1283    /// [`Self::get_descendants`] under a caller's deadline and workspace slice,
1284    /// polling once per node of the walk. Failures carry the same meaning as in
1285    /// [`Self::get_direct_descendants_within`].
1286    fn get_descendants_within(
1287        &self,
1288        code_unit: &CodeUnit,
1289        scope: &DescendantIndexScope<'_>,
1290    ) -> Result<HierarchyAnswer, Cancelled> {
1291        let mut result = None;
1292        self.with_hierarchy_query_for(code_unit, &mut |query| {
1293            result = Some(traverse_hierarchy_while(
1294                code_unit,
1295                query,
1296                scope.cancellation(),
1297                |query, next| query.direct_descendants_within(next, scope),
1298            ));
1299        });
1300        let mut answer = result.expect("hierarchy query callback runs once")?;
1301        answer.edges.sort();
1302        Ok(answer)
1303    }
1304
1305    fn get_polymorphic_matches<T: CodeUnitIndex>(
1306        &self,
1307        target: &CodeUnit,
1308        analyzer: &T,
1309    ) -> HierarchyAnswer
1310    where
1311        Self: Sized,
1312    {
1313        if !target.is_function() {
1314            return HierarchyAnswer::complete(Vec::new());
1315        }
1316
1317        let Some(parent) = analyzer.parent_of(target) else {
1318            return HierarchyAnswer::complete(Vec::new());
1319        };
1320
1321        self.get_descendants(&parent)
1322    }
1323}
1324
1325/// Exact declaration identities plus compact ancestor-to-descendant rows.
1326///
1327/// `open_candidates` are the declarations whose own ancestor answer was
1328/// open (an unresolved or ambiguous base, or a stopped proof). Their definite
1329/// ancestors are rows like any other; the rest of their ancestry is unknown, so
1330/// any of them may also descend from any other type. A row is complete only
1331/// when no other declaration is an open candidate.
1332pub struct DirectDescendantIndex {
1333    nodes: Box<[CodeUnit]>,
1334    row_by_ancestor: HashMap<CodeUnit, u32>,
1335    descendants: CompactRows<u32>,
1336    /// Any language that produces open candidates must include them in its
1337    /// descendants authority digest (for Python, `descendants_authority_digest`
1338    /// in python/mod.rs); otherwise two indexes that differ only in their open
1339    /// set would certify the same descendant answers.
1340    open_candidates: Box<[CodeUnit]>,
1341}
1342
1343impl DirectDescendantIndex {
1344    pub fn estimated_retained_bytes(&self) -> usize {
1345        let node_bytes = self
1346            .nodes
1347            .iter()
1348            .map(|unit| {
1349                std::mem::size_of::<CodeUnit>()
1350                    + unit.fq_name().len()
1351                    + unit.signature().map_or(0, str::len)
1352                    + unit.source().rel_path().as_os_str().len()
1353                    + unit.source().root().as_os_str().len()
1354            })
1355            .sum::<usize>();
1356        std::mem::size_of::<Self>()
1357            + node_bytes * 2
1358            + self.row_by_ancestor.capacity()
1359                * (std::mem::size_of::<CodeUnit>() + std::mem::size_of::<u32>() + 1)
1360            + self.descendants.estimated_bytes() as usize
1361            + self
1362                .open_candidates
1363                .iter()
1364                .map(|unit| std::mem::size_of::<CodeUnit>() + unit.fq_name().len())
1365                .sum::<usize>()
1366    }
1367
1368    pub fn from_indexed_nodes(
1369        nodes: Vec<CodeUnit>,
1370        index_by_node: HashMap<CodeUnit, u32>,
1371        mut edges: Vec<(u32, u32)>,
1372    ) -> Self {
1373        normalize_indexed_edges(&nodes, &index_by_node, &mut edges);
1374
1375        let row_count = usize::from(!edges.is_empty())
1376            + edges
1377                .windows(2)
1378                .filter(|pair| pair[0].0 != pair[1].0)
1379                .count();
1380        let mut row_by_ancestor = HashMap::default();
1381        let mut descendants = CompactRowsBuilder::with_capacity(row_count, edges.len());
1382        let mut cursor = 0;
1383        while cursor < edges.len() {
1384            let ancestor = edges[cursor].0;
1385            let start = cursor;
1386            while cursor < edges.len() && edges[cursor].0 == ancestor {
1387                cursor += 1;
1388            }
1389            let row =
1390                u32::try_from(descendants.rows()).expect("hierarchy index rows must fit in a u32");
1391            row_by_ancestor.insert(nodes[ancestor as usize].clone(), row);
1392            descendants.push_row(
1393                edges[start..cursor]
1394                    .iter()
1395                    .map(|(_, descendant)| *descendant),
1396            );
1397        }
1398        Self {
1399            nodes: nodes.into_boxed_slice(),
1400            row_by_ancestor,
1401            descendants: descendants.finish(),
1402            open_candidates: Box::default(),
1403        }
1404    }
1405
1406    /// Record the candidates whose ancestor answer is open, in `CodeUnit` order.
1407    pub fn with_open_candidates(mut self, mut open_candidates: Vec<CodeUnit>) -> Self {
1408        open_candidates.sort();
1409        open_candidates.dedup();
1410        self.open_candidates = open_candidates.into_boxed_slice();
1411        self
1412    }
1413
1414    /// The candidates whose ancestor answer is open, in `CodeUnit` order.
1415    pub fn open_candidates(&self) -> &[CodeUnit] {
1416        &self.open_candidates
1417    }
1418
1419    /// The definite descendants of `ancestor`, sorted, with the index's open
1420    /// candidates as typed incompleteness, excluding the ancestor itself.
1421    pub fn answer(&self, ancestor: &CodeUnit) -> HierarchyAnswer {
1422        let mut edges: Vec<_> = self.descendants(ancestor).into_iter().collect();
1423        edges.sort();
1424        let mut answer = HierarchyAnswer::complete(edges);
1425        let open_candidates: Vec<_> = self
1426            .open_candidates
1427            .iter()
1428            .filter(|candidate| *candidate != ancestor)
1429            .cloned()
1430            .collect();
1431        if !open_candidates.is_empty() {
1432            answer
1433                .open
1434                .push(HierarchyOpenReason::OpenAncestorCandidates(open_candidates));
1435        }
1436        answer
1437    }
1438
1439    pub fn descendants(&self, ancestor: &CodeUnit) -> HashSet<CodeUnit> {
1440        let Some(row) = self.row_by_ancestor.get(ancestor).copied() else {
1441            return HashSet::default();
1442        };
1443        self.descendants
1444            .row(row as usize)
1445            .iter()
1446            .map(|descendant| self.nodes[*descendant as usize].clone())
1447            .collect()
1448    }
1449}
1450
1451/// Invert the ancestor relation over every class the analyzer indexes.
1452///
1453/// `scope` decides two things. Its predicate drops declarations before they are
1454/// ever handed to `get_direct_ancestors`, which is where the per-declaration
1455/// resolution cost is charged (for C++ that is a whole transitive `#include`
1456/// closure per declaring file). Its token bounds the loop: `None` means the
1457/// build stopped short (including an unavailable source exclusion) and must not
1458/// be published.
1459pub fn build_direct_descendant_index<A, P>(
1460    analyzer: &A,
1461    provider: &P,
1462    scope: &DescendantIndexScope<'_>,
1463) -> Option<DirectDescendantIndex>
1464where
1465    A: CodeUnitIndex,
1466    P: TypeHierarchyProvider + ?Sized,
1467{
1468    let mut result = None;
1469    provider.with_hierarchy_query(&mut |query| {
1470        result = Some(build_direct_descendant_index_in_query(
1471            analyzer, query, scope,
1472        ));
1473    });
1474    result.expect("hierarchy query callback runs once")
1475}
1476
1477/// Invert ancestors inside an already-open query without opening another one.
1478pub fn build_direct_descendant_index_in_query<A: CodeUnitIndex>(
1479    analyzer: &A,
1480    query: &mut dyn HierarchyQuery,
1481    scope: &DescendantIndexScope<'_>,
1482) -> Option<DirectDescendantIndex> {
1483    let mut candidates = Vec::new();
1484    for candidate in analyzer.all_declarations().filter(CodeUnit::is_class) {
1485        if match scope.admits(&candidate) {
1486            Ok(value) => value,
1487            Err(reason) => {
1488                let _unavailable = reason;
1489                return None;
1490            }
1491        } {
1492            candidates.push(candidate);
1493        }
1494    }
1495    build_direct_descendant_index_from_candidates(
1496        candidates,
1497        |candidate| query.direct_ancestors_within(candidate, scope).ok(),
1498        &scope.keep_going(),
1499    )
1500}
1501
1502/// The edge-building half of [`build_direct_descendant_index`], for providers
1503/// that assemble their candidate list some other way.
1504///
1505/// `keep_going` is polled once per candidate. That granularity is the natural
1506/// checkpoint: one candidate is one `direct_ancestors` call, which is the unit
1507/// of work whose tens of thousands of repetitions made this loop unbounded in
1508/// the first place (issue #1748). `direct_ancestors` answers `None` when its
1509/// own work stopped short. A stopped answer contributes its proven edges and
1510/// remains an unbounded open candidate. Its caller retains the stop receipt
1511/// and decides whether the index can be memoized. An open answer contributes
1512/// its definite edges and makes the candidate an open candidate of the index,
1513/// unless its only open reasons name types outside the index
1514/// ([`HierarchyAnswer::keeps_indexed_edges_exact`]).
1515pub fn build_direct_descendant_index_from_candidates<F>(
1516    mut candidates: Vec<CodeUnit>,
1517    mut direct_ancestors: F,
1518    keep_going: &dyn Fn() -> bool,
1519) -> Option<DirectDescendantIndex>
1520where
1521    F: FnMut(&CodeUnit) -> Option<HierarchyAnswer>,
1522{
1523    candidates.sort();
1524    candidates.dedup();
1525    let mut types_by_fq_name: HashMap<String, Vec<CodeUnit>> = HashMap::default();
1526    for candidate in &candidates {
1527        types_by_fq_name
1528            .entry(candidate.fq_name())
1529            .or_default()
1530            .push(candidate.clone());
1531    }
1532    let mut nodes = candidates.clone();
1533    let mut index_by_node: HashMap<_, _> = nodes
1534        .iter()
1535        .enumerate()
1536        .map(|(index, node)| {
1537            (
1538                node.clone(),
1539                u32::try_from(index).expect("hierarchy index declarations must fit in a u32"),
1540            )
1541        })
1542        .collect();
1543    let mut edges = Vec::new();
1544    let mut open_candidates = Vec::new();
1545    for candidate in candidates {
1546        if !keep_going() {
1547            return None;
1548        }
1549        let descendant = index_by_node[&candidate];
1550        let answer = direct_ancestors(&candidate)?;
1551        // A clause naming a type outside the index leaves every indexed edge
1552        // known: no indexed type can descend through it, so it does not make
1553        // the candidate open (#7363).
1554        if !answer.keeps_indexed_edges_exact() {
1555            open_candidates.push(candidate.clone());
1556        }
1557        for ancestor in answer.edges {
1558            let ancestor = types_by_fq_name
1559                .get(&ancestor.fq_name())
1560                .and_then(|same_name| {
1561                    let mut same_source = same_name
1562                        .iter()
1563                        .filter(|unit| unit.source() == candidate.source());
1564                    let exact = same_source.next()?;
1565                    same_source.next().is_none().then(|| exact.clone())
1566                })
1567                .unwrap_or(ancestor);
1568            let ancestor = *index_by_node.entry(ancestor.clone()).or_insert_with(|| {
1569                let index = u32::try_from(nodes.len())
1570                    .expect("hierarchy index declarations must fit in a u32");
1571                nodes.push(ancestor);
1572                index
1573            });
1574            edges.push((ancestor, descendant));
1575        }
1576    }
1577    Some(
1578        DirectDescendantIndex::from_indexed_nodes(nodes, index_by_node, edges)
1579            .with_open_candidates(open_candidates),
1580    )
1581}
1582
1583fn traverse_hierarchy(
1584    root: &CodeUnit,
1585    query: &mut dyn HierarchyQuery,
1586    mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> HierarchyAnswer,
1587) -> HierarchyAnswer {
1588    traverse_hierarchy_edges(root, |unit| next(query, unit))
1589}
1590
1591fn traverse_hierarchy_while(
1592    root: &CodeUnit,
1593    query: &mut dyn HierarchyQuery,
1594    cancellation: &CancellationToken,
1595    mut next: impl FnMut(&mut dyn HierarchyQuery, &CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1596) -> Result<HierarchyAnswer, Cancelled> {
1597    traverse_hierarchy_edges_while(root, cancellation, |unit| next(query, unit))
1598}
1599
1600/// [`traverse_hierarchy`] under a deadline: polls once per node popped and
1601/// propagates a stopped step as `Err(Cancelled)` rather than returning the nodes it had
1602/// already collected. A partial subtype set read as complete would let a caller
1603/// conclude that a class has no further subclasses.
1604fn traverse_hierarchy_edges_while<F>(
1605    root: &CodeUnit,
1606    cancellation: &CancellationToken,
1607    mut next: F,
1608) -> Result<HierarchyAnswer, Cancelled>
1609where
1610    F: FnMut(&CodeUnit) -> Result<HierarchyAnswer, Cancelled>,
1611{
1612    let mut result = HierarchyAnswer::complete(Vec::new());
1613    let mut seen = BTreeSet::new();
1614    let mut queue = VecDeque::from([root.clone()]);
1615    while let Some(current) = queue.pop_front() {
1616        let answer = next(&current)?;
1617        result.ambiguous.extend(answer.ambiguous);
1618        for reason in answer.open {
1619            // One index's open candidates are the same at every node of the
1620            // walk; name each distinct set once.
1621            if let HierarchyOpenReason::OpenAncestorCandidates(candidates) = &reason
1622                && result.open.iter().any(|seen| {
1623                    matches!(seen, HierarchyOpenReason::OpenAncestorCandidates(other) if other == candidates)
1624                })
1625            {
1626                continue;
1627            }
1628            result.open.push(reason);
1629        }
1630        for item in answer.edges {
1631            if seen.insert(item.fq_name()) {
1632                queue.push_back(item.clone());
1633                result.edges.push(item);
1634            }
1635        }
1636        if !queue.is_empty() && cancellation.is_cancelled() {
1637            return Err(Cancelled);
1638        }
1639    }
1640    Ok(result)
1641}
1642
1643fn traverse_hierarchy_edges<F>(root: &CodeUnit, mut next: F) -> HierarchyAnswer
1644where
1645    F: FnMut(&CodeUnit) -> HierarchyAnswer,
1646{
1647    // Both variants share the traversal and completeness accounting. An owned
1648    // live token makes stopping impossible for this unscoped request.
1649    traverse_hierarchy_edges_while(root, &CancellationToken::new(), |unit| Ok(next(unit)))
1650        .expect("unscoped hierarchy traversal cannot stop")
1651}
1652
1653#[cfg(test)]
1654mod hierarchy_traversal_properties {
1655    use super::*;
1656    use crate::analyzer::model::CodeUnitType;
1657    use proptest::prelude::*;
1658    use std::collections::BTreeMap;
1659
1660    const NODES: usize = 8;
1661
1662    fn node(index: usize) -> CodeUnit {
1663        CodeUnit::new(
1664            ProjectFile::new(std::env::temp_dir(), "Hierarchy.java"),
1665            CodeUnitType::Class,
1666            "",
1667            format!("N{index}"),
1668        )
1669    }
1670
1671    #[test]
1672    fn transitive_walks_borrow_one_query_and_preserve_scoped_dispatch() {
1673        use std::sync::atomic::{AtomicUsize, Ordering};
1674        struct Provider(AtomicUsize);
1675        struct Query;
1676        impl HierarchyQuery for Query {
1677            fn direct_ancestors(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1678                let index = index_of(unit);
1679                HierarchyAnswer::complete(if index < 2 {
1680                    vec![node(index + 1)]
1681                } else {
1682                    Vec::new()
1683                })
1684            }
1685            fn direct_descendants(&mut self, unit: &CodeUnit) -> HierarchyAnswer {
1686                self.direct_ancestors(unit)
1687            }
1688            fn member_family_ancestors(&mut self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1689                MemberFamilyAncestors::default()
1690            }
1691            fn direct_descendants_within(
1692                &mut self,
1693                _unit: &CodeUnit,
1694                _scope: &DescendantIndexScope<'_>,
1695            ) -> Result<HierarchyAnswer, Cancelled> {
1696                Err(Cancelled)
1697            }
1698        }
1699        impl TypeHierarchyProvider for Provider {
1700            fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1701                panic!("the walk must use its query")
1702            }
1703            fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1704                panic!("the walk must use its query")
1705            }
1706            fn with_hierarchy_query(&self, run: &mut dyn FnMut(&mut dyn HierarchyQuery)) {
1707                self.0.fetch_add(1, Ordering::Relaxed);
1708                run(&mut Query);
1709            }
1710        }
1711        let provider = Provider(AtomicUsize::new(0));
1712        assert_eq!(
1713            provider.get_ancestors(&node(0)).edges,
1714            vec![node(1), node(2)]
1715        );
1716        assert_eq!(provider.0.load(Ordering::Relaxed), 1);
1717        assert_eq!(
1718            provider.get_descendants(&node(0)).edges,
1719            vec![node(1), node(2)]
1720        );
1721        assert_eq!(provider.0.load(Ordering::Relaxed), 2);
1722        let cancellation = CancellationToken::new();
1723        assert!(
1724            provider
1725                .get_descendants_within(
1726                    &node(0),
1727                    &DescendantIndexScope::whole_workspace(&cancellation)
1728                )
1729                .is_err()
1730        );
1731        assert_eq!(provider.0.load(Ordering::Relaxed), 3);
1732    }
1733
1734    #[test]
1735    fn default_query_forwards_scoped_provider_overrides() {
1736        struct Provider;
1737        impl TypeHierarchyProvider for Provider {
1738            fn get_direct_ancestors(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1739                HierarchyAnswer::complete(vec![node(1)])
1740            }
1741            fn get_direct_descendants(&self, _unit: &CodeUnit) -> HierarchyAnswer {
1742                HierarchyAnswer::complete(vec![node(2)])
1743            }
1744            fn get_direct_ancestors_within(
1745                &self,
1746                _unit: &CodeUnit,
1747                _scope: &DescendantIndexScope<'_>,
1748            ) -> Result<HierarchyAnswer, Cancelled> {
1749                Err(Cancelled)
1750            }
1751            fn member_family_ancestors(&self, _unit: &CodeUnit) -> MemberFamilyAncestors {
1752                MemberFamilyAncestors {
1753                    resolved: vec![node(3)],
1754                    ..Default::default()
1755                }
1756            }
1757        }
1758        let cancellation = CancellationToken::new();
1759        Provider.with_hierarchy_query(&mut |query| {
1760            assert_eq!(query.direct_ancestors(&node(0)).edges, vec![node(1)]);
1761            assert_eq!(query.direct_descendants(&node(0)).edges, vec![node(2)]);
1762            assert_eq!(
1763                query.member_family_ancestors(&node(0)).resolved,
1764                vec![node(3)]
1765            );
1766            assert!(
1767                query
1768                    .direct_ancestors_within(
1769                        &node(0),
1770                        &DescendantIndexScope::whole_workspace(&cancellation)
1771                    )
1772                    .is_err()
1773            );
1774        });
1775    }
1776
1777    fn index_of(unit: &CodeUnit) -> usize {
1778        unit.fq_name()[1..].parse().expect("test node name")
1779    }
1780
1781    #[test]
1782    fn closure_preserves_uncertainty_without_traversing_alternatives() {
1783        let mut visited = Vec::new();
1784        let answer = traverse_hierarchy_edges(&node(0), |unit| {
1785            let id = index_of(unit);
1786            visited.push(id);
1787            match id {
1788                0 => HierarchyAnswer {
1789                    edges: vec![node(1), node(1)],
1790                    ambiguous: vec![vec![node(2), node(3)]],
1791                    open: Vec::new(),
1792                },
1793                1 => HierarchyAnswer {
1794                    edges: Vec::new(),
1795                    ambiguous: vec![vec![node(4), node(5)]],
1796                    open: vec![HierarchyOpenReason::UnreadAncestor(
1797                        UnreadMemberFamilyAncestor {
1798                            name: "External".into(),
1799                            inventory: None,
1800                        },
1801                    )],
1802                },
1803                _ => panic!("ambiguous alternatives must not be traversed"),
1804            }
1805        });
1806        assert_eq!(visited, vec![0, 1]);
1807        assert_eq!(answer.edges, vec![node(1)]);
1808        assert_eq!(
1809            answer.ambiguous,
1810            vec![vec![node(2), node(3)], vec![node(4), node(5)]]
1811        );
1812        assert!(
1813            matches!(answer.open.as_slice(), [HierarchyOpenReason::UnreadAncestor(ancestor)] if ancestor.name == "External")
1814        );
1815        assert!(!answer.is_complete());
1816    }
1817
1818    #[test]
1819    #[brokk_bifrost_test_macros::hardwon(
1820        "#12211: an open candidate tainted its own descendant answer"
1821    )]
1822    #[brokk_bifrost_test_macros::hardwon(
1823        "#12172: an open candidate's own ancestry tainted its descendant query"
1824    )]
1825    fn an_open_candidate_does_not_taint_its_own_descendants() {
1826        let project = ProjectFile::new(std::env::temp_dir(), "Hierarchy.java");
1827        let class = |name: &str| CodeUnit::new(project.clone(), CodeUnitType::Class, "", name);
1828        let base = class("Base");
1829        let open = class("Open");
1830        let derived = class("Derived");
1831        let index = build_direct_descendant_index_from_candidates(
1832            vec![base.clone(), open.clone(), derived.clone()],
1833            |candidate| {
1834                if candidate == &open {
1835                    Some(HierarchyAnswer {
1836                        edges: vec![base.clone()],
1837                        open: vec![HierarchyOpenReason::UnreadAncestor(
1838                            UnreadMemberFamilyAncestor {
1839                                name: "Mystery".into(),
1840                                inventory: None,
1841                            },
1842                        )],
1843                        ambiguous: Vec::new(),
1844                    })
1845                } else if candidate == &derived {
1846                    Some(HierarchyAnswer::complete(vec![open.clone()]))
1847                } else {
1848                    Some(HierarchyAnswer::complete(Vec::new()))
1849                }
1850            },
1851            &|| true,
1852        )
1853        .expect("finished open answers build an index");
1854
1855        let base_answer = index.answer(&base);
1856        assert!(!base_answer.is_complete());
1857        assert!(matches!(
1858            base_answer.open.as_slice(),
1859            [HierarchyOpenReason::OpenAncestorCandidates(candidates)]
1860                if candidates == std::slice::from_ref(&open)
1861        ));
1862
1863        let own = index.answer(&open);
1864        assert!(own.is_complete(), "{own:?}");
1865        assert_eq!(own.edges, vec![derived]);
1866    }
1867
1868    /// Edge lists may repeat a target, hold self loops and form cycles.
1869    fn graphs() -> impl Strategy<Value = Vec<Vec<usize>>> {
1870        proptest::collection::vec(proptest::collection::vec(0..NODES, 0..5), NODES)
1871    }
1872
1873    /// Reference by relaxation: `distance[n]` is the fewest edges on a path
1874    /// from `root` to `n` that uses at least one edge. This makes the root
1875    /// reachable only through a cycle, which is what the traversal reports.
1876    fn reference_distances(graph: &[Vec<usize>], root: usize) -> BTreeMap<usize, usize> {
1877        let mut distance: BTreeMap<usize, usize> = BTreeMap::new();
1878        for &next in &graph[root] {
1879            distance.insert(next, 1);
1880        }
1881        loop {
1882            let mut changed = false;
1883            for (from, edges) in graph.iter().enumerate() {
1884                let Some(&base) = distance.get(&from) else {
1885                    continue;
1886                };
1887                for &to in edges {
1888                    if distance.get(&to).is_none_or(|&known| known > base + 1) {
1889                        distance.insert(to, base + 1);
1890                        changed = true;
1891                    }
1892                }
1893            }
1894            if !changed {
1895                return distance;
1896            }
1897        }
1898    }
1899
1900    proptest! {
1901        #![proptest_config(ProptestConfig::with_cases(128))]
1902
1903        /// On any graph, cyclic or not, the traversal terminates, returns each
1904        /// reachable declaration exactly once in breadth-first order, and asks
1905        /// for each declaration's neighbours once (the root twice when a cycle
1906        /// returns to it).
1907        #[test]
1908        fn visits_exactly_the_reachable_set_once_in_breadth_first_order(
1909            graph in graphs(),
1910            root in 0..NODES,
1911        ) {
1912            let mut calls: BTreeMap<usize, usize> = BTreeMap::new();
1913            let result = traverse_hierarchy_edges(&node(root), |unit| {
1914                let id = index_of(unit);
1915                *calls.entry(id).or_default() += 1;
1916                HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())
1917            });
1918            let found: Vec<usize> = result.edges.iter().map(index_of).collect();
1919
1920            let distance = reference_distances(&graph, root);
1921            let unique: BTreeSet<usize> = found.iter().copied().collect();
1922            prop_assert_eq!(found.len(), unique.len(), "a declaration was returned twice: {:?}", found);
1923            prop_assert_eq!(unique, distance.keys().copied().collect::<BTreeSet<_>>());
1924            prop_assert!(
1925                found.windows(2).all(|pair| distance[&pair[0]] <= distance[&pair[1]]),
1926                "not breadth-first: {:?} with distances {:?}", found, distance
1927            );
1928            // The root is not in the seen set when the walk starts, so a cycle
1929            // back to it expands it a second time; every other node once.
1930            prop_assert!(
1931                calls.iter().all(|(&id, &count)| count == 1 || (id == root && count == 2)),
1932                "repeated expansion: {:?}", calls
1933            );
1934
1935            // The deadline-aware variant agrees when never cancelled.
1936            let live = CancellationToken::new();
1937            let guarded = traverse_hierarchy_edges_while(&node(root), &live, |unit| {
1938                Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1939            });
1940            let guarded = guarded.expect("live traversal");
1941            prop_assert!(guarded.is_complete());
1942            prop_assert_eq!(guarded.edges, result.edges);
1943        }
1944
1945        /// A failed neighbour step is propagated, not hidden behind a partial
1946        /// answer; a cancelled token stops a traversal that has work left but
1947        /// does not disturb one whose root has no neighbours.
1948        #[test]
1949        fn guarded_traversal_never_returns_a_partial_answer(
1950            graph in graphs(),
1951            root in 0..NODES,
1952            fail_on in 0..NODES,
1953        ) {
1954            let reachable = reference_distances(&graph, root);
1955            let failing = traverse_hierarchy_edges_while(&node(root), &CancellationToken::new(), |unit| {
1956                let id = index_of(unit);
1957                if id == fail_on { Err(Cancelled) } else { Ok(HierarchyAnswer::complete(graph[id].iter().map(|&to| node(to)).collect())) }
1958            });
1959            // The failing node's neighbours are requested when it is the root or
1960            // is itself returned, so it is only skipped when neither holds.
1961            let requested = fail_on == root || reachable.contains_key(&fail_on);
1962            prop_assert_eq!(failing.is_err(), requested);
1963
1964            let cancelled = CancellationToken::new();
1965            cancelled.cancel();
1966            let stopped = traverse_hierarchy_edges_while(&node(root), &cancelled, |unit| {
1967                Ok(HierarchyAnswer::complete(graph[index_of(unit)].iter().map(|&to| node(to)).collect()))
1968            });
1969            prop_assert_eq!(stopped.is_err(), !graph[root].is_empty());
1970            if graph[root].is_empty() {
1971                let stopped = stopped.expect("empty traversal");
1972                prop_assert!(stopped.is_complete());
1973                prop_assert!(stopped.edges.is_empty());
1974            }
1975        }
1976    }
1977}