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::declarations::CppRecoveredExportClassIndex;
29use crate::graph::CppWorkspaceSource;
30use crate::graph::resolver::{
31 CppClassDeclarationStrength, OrphanedNamespaceScopeIndex, SourceUsingIndex,
32};
33use crate::identity::CppCallableUnitRole;
34use crate::imports::IncludeTargetIndex;
35use brokk_bifrost_core::analyzer::capabilities::{TypeAliasProvider, TypeHierarchyProvider};
36use brokk_bifrost_core::analyzer::model::{CppFieldLinkage, CppTemplateMetadata};
37use brokk_bifrost_core::analyzer::prepared_syntax::PreparedSyntaxTree;
38use brokk_bifrost_core::analyzer::query_token::QueryToken;
39use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, ProjectFile};
40use std::collections::BTreeSet;
41use std::sync::Arc;
42
43pub trait CppSource:
44 CodeUnitIndex + TypeAliasProvider + TypeHierarchyProvider + CppWorkspaceSource
45{
46 /// Structured includes for a disposable visibility traversal.
47 fn visibility_import_statements(
48 &self,
49 _token: QueryToken<'_>,
50 file: &ProjectFile,
51 ) -> Vec<String> {
52 self.import_statements(file)
53 }
54
55 /// Physical identifier candidates used only to discover source files for
56 /// a bounded visibility traversal. Re-keyed out-of-line definitions do not
57 /// add an includable source, so analyzer implementations may answer this
58 /// from their stored declaration index without global identity
59 /// reconciliation.
60 fn visibility_identifier_candidates(&self, identifier: &str) -> BTreeSet<CodeUnit> {
61 self.lookup_candidates_by_identifier(identifier)
62 }
63
64 /// The callable role recorded for a physical stored declaration, without
65 /// consulting reconciliation fallbacks that may themselves be building.
66 fn stored_callable_unit_role(&self, callable: &CodeUnit) -> CppCallableUnitRole;
67
68 /// The workspace-wide `#include` resolution table, built once per analyzer
69 /// generation from [`IncludeTargetIndex::build`].
70 fn include_target_index(&self) -> &IncludeTargetIndex;
71
72 /// The declared base specifiers of `code_unit`, as written
73 /// (`TreeSitterAnalyzer::raw_supertypes_of`).
74 fn raw_supertypes_of(&self, code_unit: &CodeUnit) -> Vec<String>;
75
76 /// Every class-like or alias declaration reachable from `file` through its
77 /// `#include` closure, memoized per file. See this module's note.
78 fn visible_type_units(&self, file: &ProjectFile) -> Arc<Vec<CodeUnit>>;
79
80 /// [`Self::visible_type_units`] under a caller's deadline.
81 ///
82 /// `None` means the include-closure walk stopped short. Nothing is
83 /// memoized in that case: a truncated class table is indistinguishable
84 /// from a file that simply sees fewer types, so every later base-specifier
85 /// resolution reading it would silently lose ancestors.
86 ///
87 /// This is the shape issue #1748 needed. The closure walk is individually
88 /// cheap -- a fraction of a millisecond to about 180 ms -- but the
89 /// descendant-index build above it runs one per class in the workspace,
90 /// which on a large tree is tens of thousands of them inside a single
91 /// request that asked for thirty seconds.
92 fn visible_type_units_while(
93 &self,
94 file: &ProjectFile,
95 keep_going: &dyn Fn() -> bool,
96 ) -> Option<Arc<Vec<CodeUnit>>>;
97
98 /// The per-file structured using index (ordinary using declarations and
99 /// using-directives with their guard environments), memoized per file.
100 /// Built by [`crate::graph::extractor::build_source_using_index`], which is
101 /// a pure function of the file's parsed content.
102 ///
103 /// Memoized on the analyzer rather than on `VisibilityIndex` because a
104 /// fresh visibility index is built per usage query: rebuilding the index
105 /// per query re-walked a 9.5 MB amalgamation's AST once per candidate
106 /// (issue #1927).
107 fn source_using_index(
108 &self,
109 token: QueryToken<'_>,
110 file: &ProjectFile,
111 ) -> Arc<SourceUsingIndex>;
112
113 /// The indexed source of `file` (`TreeSitterAnalyzer::file_source`).
114 fn file_source(&self, file: &ProjectFile) -> Option<String>;
115
116 /// The parsed tree and its source backing for `file`, from the analyzer's
117 /// query read cache.
118 ///
119 /// The single hottest member of this trait: the usage graph reaches it at
120 /// 27 call sites. The cache is *not* rebuilt per call -- `VisibilityIndex`
121 /// borrows the analyzer rather than cloning it precisely so this stays warm
122 /// across a scan (#1175), so an implementor must forward to the same
123 /// analyzer the query is running against.
124 ///
125 /// The [`QueryToken`] is proof that a request scope is open, so the cache
126 /// this reads is live (issue #2414 step 3).
127 fn prepared_syntax(
128 &self,
129 token: QueryToken<'_>,
130 file: &ProjectFile,
131 ) -> Option<Arc<PreparedSyntaxTree>>;
132
133 /// The persisted linkage fact for one C++ field, when the parser recorded
134 /// it. A missing fact requires the resolver's syntax fallback.
135 fn cpp_field_linkage(&self, code_unit: &CodeUnit) -> Option<CppFieldLinkage>;
136
137 /// The cached result of a preprocessor-visible include-reachability walk.
138 ///
139 /// The reference language affects only `__cplusplus` guards. Callers pass
140 /// that fact as a Boolean so cache keys do not retain the full reference
141 /// path.
142 fn cached_unconditional_include_reachability(
143 &self,
144 first: &ProjectFile,
145 donor_source: &ProjectFile,
146 reference_is_c: bool,
147 ) -> Option<bool>;
148
149 /// Store a completed preprocessor-visible include-reachability walk.
150 fn cache_unconditional_include_reachability(
151 &self,
152 first: &ProjectFile,
153 donor_source: &ProjectFile,
154 reference_is_c: bool,
155 reaches: bool,
156 );
157
158 /// The file's embedded export-macro class recovery, resolved once per file.
159 ///
160 /// Built by [`crate::declarations::CppRecoveredExportClassIndex::build`],
161 /// which is a pure function of the file's parsed content. Memoized on the
162 /// analyzer for the same reason as [`Self::source_using_index`]: the
163 /// declaration-strength question asks it once per class-like unit, and
164 /// re-deriving it walks and sorts every `ERROR` subtree in the file (#1496).
165 fn recovered_export_class_index(
166 &self,
167 token: QueryToken<'_>,
168 file: &ProjectFile,
169 ) -> Arc<CppRecoveredExportClassIndex>;
170
171 /// The namespaces C++ parse recovery dropped from `file`'s tree, resolved
172 /// once per file.
173 ///
174 /// Built by [`OrphanedNamespaceScopeIndex::build`], a pure function of the
175 /// file's parsed content, and empty for a file without parse errors. Both
176 /// lookup directions derive every lexical scope in the file through it, so
177 /// it is memoized on the analyzer like [`Self::source_using_index`] rather
178 /// than rebuilt per query or per reference (issue #1537).
179 fn orphaned_namespace_scopes(
180 &self,
181 token: QueryToken<'_>,
182 file: &ProjectFile,
183 ) -> Arc<OrphanedNamespaceScopeIndex>;
184
185 /// The memoized answer of
186 /// [`crate::graph::resolver::cpp_class_declaration_strength`] for one
187 /// class-like unit, when a previous ask stored it.
188 ///
189 /// The answer is a pure function of the unit's declaration ranges and its
190 /// file's parse tree, so it is stable for an analyzer generation. Memoized
191 /// on the analyzer for the same reason as [`Self::source_using_index`]: the
192 /// inverse scan asks it once per declaration seed, and on a translation
193 /// unit the parser could not fully recover each ask re-derives the
194 /// export-macro recovery shapes from the file's `ERROR` subtrees, which is
195 /// quadratic in the file's size (#1496).
196 fn cached_class_declaration_strength(
197 &self,
198 candidate: &CodeUnit,
199 ) -> Option<CppClassDeclarationStrength>;
200
201 /// Store a completed declaration-strength answer.
202 fn cache_class_declaration_strength(
203 &self,
204 candidate: &CodeUnit,
205 strength: CppClassDeclarationStrength,
206 );
207
208 /// The declaration's syntactic owner, which unlike
209 /// [`CodeUnitIndex::parent_of`] never falls back to a definition-row lookup.
210 fn structural_parent_of(&self, code_unit: &CodeUnit) -> Option<CodeUnit>;
211
212 /// The persisted C++ template metadata side table's row for `code_unit`.
213 fn template_metadata(&self, code_unit: &CodeUnit) -> Option<CppTemplateMetadata>;
214
215 /// Whether a reference written in the header `file` reads the declarations
216 /// it can see with C semantics: every workspace translation unit that
217 /// provably compiles this header compiles it as C (issue #1970).
218 ///
219 /// Always false for a translation unit -- its own extension settles its
220 /// dialect, which [`crate::graph::resolver::is_c_source_file`] answers
221 /// without asking the analyzer. Both halves are combined by
222 /// [`crate::graph::resolver::reference_uses_c_semantics`], the one helper
223 /// resolution asks.
224 ///
225 /// A header both languages provably include reports false: forward
226 /// resolution from it reports the C++ identity, and the site-equivalence
227 /// union below is what keeps inverse in agreement.
228 fn header_uses_c_semantics(&self, file: &ProjectFile) -> bool;
229
230 /// The declarations of `file` as one of its two readings sees them.
231 ///
232 /// `c_semantics` false is the C++ reading, which is exactly
233 /// [`CodeUnitIndex::declarations`]. True is the C reading: the stored
234 /// `cpp:c` row-set when the blob has one, and otherwise the same C++
235 /// row-set, because "no C rows" means the two readings agree.
236 ///
237 /// Candidate enumeration selects a reading here and nowhere else: include
238 /// activation, preprocessor-guard compatibility, block-scope shadowing and
239 /// ambiguity all run unchanged over whichever set comes back.
240 fn declarations_in_reading(&self, file: &ProjectFile, c_semantics: bool) -> BTreeSet<CodeUnit>;
241
242 /// The identities of the other reading that share `code_unit`'s
243 /// declaration site -- the same source file and the same declaration byte
244 /// range -- empty when the two readings agree about it.
245 ///
246 /// Keyed on the range, never on a name. Inverse results are unioned across
247 /// these so a query against either identity of one declaration reports
248 /// every reference found under both readings.
249 fn site_equivalent_units(&self, code_unit: &CodeUnit) -> Vec<CodeUnit>;
250
251 /// Every distinct `compile_commands.json` configuration governing `file`,
252 /// empty when the workspace has no compile database entry naming it. The
253 /// only analyzer-resident product [`crate::diagnostics`] needs.
254 ///
255 /// A file the build compiles in several configurations yields several
256 /// contexts, because their include closures can disagree about a name.
257 fn compile_contexts_for(&self, file: &ProjectFile) -> &[CppCompileContext];
258
259 /// Every workspace translation unit whose `#include` closure transitively
260 /// reaches `file` -- the header-to-TU attribution map from #1970's
261 /// Milestone 2, which #2011 phase 2 reads for header-sited guard proof.
262 /// Empty when nothing reaches `file` or the implementor has no include
263 /// graph, which conservatively yields no compile-context facts.
264 fn reaching_translation_units(&self, _file: &ProjectFile) -> Vec<ProjectFile> {
265 Vec::new()
266 }
267
268 /// Count a precise-parent resolution against the analyzer's counter.
269 ///
270 /// Called from production code in [`crate::graph::resolver`], which is why
271 /// it is on the trait at all; the counter itself stays on the analyzer.
272 ///
273 /// The default is a no-op because the two gates are not the same gate:
274 /// Cargo turns this crate's `test-support` on for the whole build graph
275 /// whenever `brokk-bifrost-analysis`'s dev-dependencies are in play, while
276 /// the analyzer-side counter field is `#[cfg(any(test, feature =
277 /// "test-support"))]` on *that* crate. The implementor overrides this
278 /// exactly when it has a counter to record into -- which is the build the
279 /// tests reading the counter run in.
280 #[cfg(any(test, feature = "test-support"))]
281 fn record_cpp_parent_resolution_for_test(&self) {}
282
283 /// Count a class-declaration-strength parse. See
284 /// [`Self::record_cpp_parent_resolution_for_test`].
285 #[cfg(any(test, feature = "test-support"))]
286 fn record_cpp_class_strength_parse_for_test(&self) {}
287
288 /// Count a guard-ancestry inspection during a per-file using-index build.
289 /// See [`Self::record_cpp_parent_resolution_for_test`].
290 #[cfg(any(test, feature = "test-support"))]
291 fn record_using_guard_context_inspection_for_test(&self) {}
292}