brokk_bifrost_cpp/graph_support.rs
1//! The analyzer-resident products C++'s language logic resolves through.
2//!
3//! `CppAnalyzer` owns five moka caches, three `Arc<OnceLock<..>>` cells and one
4//! `PoolSafeMemo`; every one of them stays in `brokk-bifrost-analysis` because
5//! `IAnalyzer::update`/`update_all` rebuild the analyzer wholesale through
6//! `Self::from_inner`. What crosses the crate line is the *decision* that fills
7//! each cell -- the builders in [`crate::hierarchy`], [`crate::identity`] and
8//! [`crate::imports`] -- plus this trait, which is how a free function reaches
9//! back for a memoized product without naming the analyzer type.
10//!
11//! The census found no re-entrancy among these accessors, so this is a single
12//! tier rather than the two-tier split some fleet languages needed: the #1134
13//! reconciliation reads `visible_type_units`, which reads `include_target_index`
14//! and the supertrait's `import_statements`, and none of those reads back into
15//! reconciliation.
16//!
17//! Three members are load-bearing beyond their signature:
18//!
19//! * [`CppSource::visible_type_units`] is the moka-cached include-closure
20//! class table. Its *builder* is [`crate::hierarchy::build_cpp_visible_type_units`];
21//! the cell and its `test-support` build counter stay analyzer-side, so this
22//! accessor is the only way the reconciler reaches a warm table.
23//! * [`CppSource::raw_supertypes_of`] is
24//! `TreeSitterAnalyzer::raw_supertypes_of`, whose rows are crate-private to
25//! analysis; the analyzer hands the decoded base-specifier strings across.
26
27use crate::compile_context::CppCompileContext;
28use crate::graph::CppWorkspaceSource;
29use crate::graph::resolver::SourceUsingIndex;
30use crate::imports::IncludeTargetIndex;
31use brokk_bifrost_core::analyzer::capabilities::{TypeAliasProvider, TypeHierarchyProvider};
32use brokk_bifrost_core::analyzer::model::{CppFieldLinkage, CppTemplateMetadata};
33use brokk_bifrost_core::analyzer::prepared_syntax::PreparedSyntaxTree;
34use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, ProjectFile};
35use std::collections::BTreeSet;
36use std::sync::Arc;
37
38pub trait CppSource:
39 CodeUnitIndex + TypeAliasProvider + TypeHierarchyProvider + CppWorkspaceSource
40{
41 /// The workspace-wide `#include` resolution table, built once per analyzer
42 /// generation from [`IncludeTargetIndex::build`].
43 fn include_target_index(&self) -> &IncludeTargetIndex;
44
45 /// The declared base specifiers of `code_unit`, as written
46 /// (`TreeSitterAnalyzer::raw_supertypes_of`).
47 fn raw_supertypes_of(&self, code_unit: &CodeUnit) -> Vec<String>;
48
49 /// Every class-like or alias declaration reachable from `file` through its
50 /// `#include` closure, memoized per file. See this module's note.
51 fn visible_type_units(&self, file: &ProjectFile) -> Arc<Vec<CodeUnit>>;
52
53 /// [`Self::visible_type_units`] under a caller's deadline.
54 ///
55 /// `None` means the include-closure walk stopped short. Nothing is
56 /// memoized in that case: a truncated class table is indistinguishable
57 /// from a file that simply sees fewer types, so every later base-specifier
58 /// resolution reading it would silently lose ancestors.
59 ///
60 /// This is the shape issue #1748 needed. The closure walk is individually
61 /// cheap -- a fraction of a millisecond to about 180 ms -- but the
62 /// descendant-index build above it runs one per class in the workspace,
63 /// which on a large tree is tens of thousands of them inside a single
64 /// request that asked for thirty seconds.
65 fn visible_type_units_while(
66 &self,
67 file: &ProjectFile,
68 keep_going: &dyn Fn() -> bool,
69 ) -> Option<Arc<Vec<CodeUnit>>>;
70
71 /// The per-file structured using index (ordinary using declarations and
72 /// using-directives with their guard environments), memoized per file.
73 /// Built by [`crate::graph::extractor::build_source_using_index`], which is
74 /// a pure function of the file's parsed content.
75 ///
76 /// Memoized on the analyzer rather than on `VisibilityIndex` because a
77 /// fresh visibility index is built per usage query: rebuilding the index
78 /// per query re-walked a 9.5 MB amalgamation's AST once per candidate
79 /// (issue #1927).
80 fn source_using_index(&self, file: &ProjectFile) -> Arc<SourceUsingIndex>;
81
82 /// The indexed source of `file` (`TreeSitterAnalyzer::file_source`).
83 fn file_source(&self, file: &ProjectFile) -> Option<String>;
84
85 /// The parsed tree and its source backing for `file`, from the analyzer's
86 /// query read cache.
87 ///
88 /// The single hottest member of this trait: the usage graph reaches it at
89 /// 27 call sites. The cache is *not* rebuilt per call -- `VisibilityIndex`
90 /// borrows the analyzer rather than cloning it precisely so this stays warm
91 /// across a scan (#1175), so an implementor must forward to the same
92 /// analyzer the query is running against.
93 fn prepared_syntax(&self, file: &ProjectFile) -> Option<Arc<PreparedSyntaxTree>>;
94
95 /// The persisted linkage fact for one C++ field, when the parser recorded
96 /// it. A missing fact requires the resolver's syntax fallback.
97 fn cpp_field_linkage(&self, code_unit: &CodeUnit) -> Option<CppFieldLinkage>;
98
99 /// The cached result of a preprocessor-visible include-reachability walk.
100 ///
101 /// The reference language affects only `__cplusplus` guards. Callers pass
102 /// that fact as a Boolean so cache keys do not retain the full reference
103 /// path.
104 fn cached_unconditional_include_reachability(
105 &self,
106 first: &ProjectFile,
107 donor_source: &ProjectFile,
108 reference_is_c: bool,
109 ) -> Option<bool>;
110
111 /// Store a completed preprocessor-visible include-reachability walk.
112 fn cache_unconditional_include_reachability(
113 &self,
114 first: &ProjectFile,
115 donor_source: &ProjectFile,
116 reference_is_c: bool,
117 reaches: bool,
118 );
119
120 /// The declaration's syntactic owner, which unlike
121 /// [`CodeUnitIndex::parent_of`] never falls back to a definition-row lookup.
122 fn structural_parent_of(&self, code_unit: &CodeUnit) -> Option<CodeUnit>;
123
124 /// The persisted C++ template metadata side table's row for `code_unit`.
125 fn template_metadata(&self, code_unit: &CodeUnit) -> Option<CppTemplateMetadata>;
126
127 /// Whether a reference written in the header `file` reads the declarations
128 /// it can see with C semantics: every workspace translation unit that
129 /// provably compiles this header compiles it as C (issue #1970).
130 ///
131 /// Always false for a translation unit -- its own extension settles its
132 /// dialect, which [`crate::graph::resolver::is_c_source_file`] answers
133 /// without asking the analyzer. Both halves are combined by
134 /// [`crate::graph::resolver::reference_uses_c_semantics`], the one helper
135 /// resolution asks.
136 ///
137 /// A header both languages provably include reports false: forward
138 /// resolution from it reports the C++ identity, and the site-equivalence
139 /// union below is what keeps inverse in agreement.
140 fn header_uses_c_semantics(&self, file: &ProjectFile) -> bool;
141
142 /// The declarations of `file` as one of its two readings sees them.
143 ///
144 /// `c_semantics` false is the C++ reading, which is exactly
145 /// [`CodeUnitIndex::declarations`]. True is the C reading: the stored
146 /// `cpp:c` row-set when the blob has one, and otherwise the same C++
147 /// row-set, because "no C rows" means the two readings agree.
148 ///
149 /// Candidate enumeration selects a reading here and nowhere else: include
150 /// activation, preprocessor-guard compatibility, block-scope shadowing and
151 /// ambiguity all run unchanged over whichever set comes back.
152 fn declarations_in_reading(&self, file: &ProjectFile, c_semantics: bool) -> BTreeSet<CodeUnit>;
153
154 /// The identities of the other reading that share `code_unit`'s
155 /// declaration site -- the same source file and the same declaration byte
156 /// range -- empty when the two readings agree about it.
157 ///
158 /// Keyed on the range, never on a name. Inverse results are unioned across
159 /// these so a query against either identity of one declaration reports
160 /// every reference found under both readings.
161 fn site_equivalent_units(&self, code_unit: &CodeUnit) -> Vec<CodeUnit>;
162
163 /// Every distinct `compile_commands.json` configuration governing `file`,
164 /// empty when the workspace has no compile database entry naming it. The
165 /// only analyzer-resident product [`crate::diagnostics`] needs.
166 ///
167 /// A file the build compiles in several configurations yields several
168 /// contexts, because their include closures can disagree about a name.
169 fn compile_contexts_for(&self, file: &ProjectFile) -> &[CppCompileContext];
170
171 /// Every workspace translation unit whose `#include` closure transitively
172 /// reaches `file` -- the header-to-TU attribution map from #1970's
173 /// Milestone 2, which #2011 phase 2 reads for header-sited guard proof.
174 /// Empty when nothing reaches `file` or the implementor has no include
175 /// graph, which conservatively yields no compile-context facts.
176 fn reaching_translation_units(&self, _file: &ProjectFile) -> Vec<ProjectFile> {
177 Vec::new()
178 }
179
180 /// Count a precise-parent resolution against the analyzer's counter.
181 ///
182 /// Called from production code in [`crate::graph::resolver`], which is why
183 /// it is on the trait at all; the counter itself stays on the analyzer.
184 ///
185 /// The default is a no-op because the two gates are not the same gate:
186 /// Cargo turns this crate's `test-support` on for the whole build graph
187 /// whenever `brokk-bifrost-analysis`'s dev-dependencies are in play, while
188 /// the analyzer-side counter field is `#[cfg(any(test, feature =
189 /// "test-support"))]` on *that* crate. The implementor overrides this
190 /// exactly when it has a counter to record into -- which is the build the
191 /// tests reading the counter run in.
192 #[cfg(any(test, feature = "test-support"))]
193 fn record_cpp_parent_resolution_for_test(&self) {}
194
195 /// Count a class-declaration-strength parse. See
196 /// [`Self::record_cpp_parent_resolution_for_test`].
197 #[cfg(any(test, feature = "test-support"))]
198 fn record_cpp_class_strength_parse_for_test(&self) {}
199
200 /// Count a guard-ancestry inspection during a per-file using-index build.
201 /// See [`Self::record_cpp_parent_resolution_for_test`].
202 #[cfg(any(test, feature = "test-support"))]
203 fn record_using_guard_context_inspection_for_test(&self) {}
204}