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//! The visible-type table remains analyzer-owned:
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
24use crate::compile_context::CppCompileContext;
25use crate::declarations::CppRecoveredExportClassIndex;
26use crate::graph::CppWorkspaceSource;
27use crate::graph::resolver::{
28 CppClassDeclarationStrength, OrphanedNamespaceScopeIndex, SourceUsingIndex,
29};
30use crate::identity::CppCallableUnitRole;
31use crate::imports::{IncludeTargetIndex, canonical_include_paths, canonical_include_statements};
32use brokk_bifrost_core::analyzer::capabilities::{TypeAliasProvider, TypeHierarchyProvider};
33use brokk_bifrost_core::analyzer::model::{
34 CppFieldLinkage, CppTemplateMetadata, SignatureMetadata,
35};
36use brokk_bifrost_core::analyzer::prepared_syntax::PreparedSyntaxTree;
37use brokk_bifrost_core::analyzer::query_token::QueryToken;
38use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, ProjectFile};
39use brokk_bifrost_core::cancellation::CancellationToken;
40use brokk_bifrost_core::hash::{HashMap, HashSet};
41use std::collections::BTreeSet;
42use std::sync::Arc;
43
44pub trait CppSource:
45 CodeUnitIndex + TypeAliasProvider + TypeHierarchyProvider + CppWorkspaceSource
46{
47 /// Canonical declaration syntax for the file's primary compilation reading.
48 fn declaration_source_facts(
49 &self,
50 _token: QueryToken<'_>,
51 _file: &ProjectFile,
52 ) -> Option<Arc<crate::source_facts::CppFileSourceFacts>> {
53 None
54 }
55
56 /// Canonical AST-owned include facts for the file's primary reading.
57 /// `None` means source-facts publication is unavailable; an empty vector
58 /// is an authoritative include-free file.
59 fn canonical_include_facts(
60 &self,
61 token: QueryToken<'_>,
62 file: &ProjectFile,
63 ) -> Option<Vec<brokk_bifrost_core::analyzer::cpp_facts::CppIncludeFact>> {
64 self.declaration_source_facts(token, file)
65 .map(|source| source.facts.includes.clone())
66 }
67
68 /// Canonical include paths for a file's primary reading.
69 fn canonical_include_paths(
70 &self,
71 token: QueryToken<'_>,
72 file: &ProjectFile,
73 ) -> Option<Vec<String>> {
74 self.declaration_source_facts(token, file)
75 .map(|source| canonical_include_paths(&source))
76 }
77
78 /// Exact source alternatives for a mounted declaration. Unavailable source
79 /// publication stays unknown; consumers must never reparse the candidate.
80 fn declaration_source_properties(
81 &self,
82 token: QueryToken<'_>,
83 unit: &CodeUnit,
84 ) -> Option<Vec<brokk_bifrost_core::analyzer::cpp_facts::CppDeclarationSourceFact>> {
85 let source = self.declaration_source_facts(token, unit.source())?;
86 let facts: Vec<_> = source.for_unit(unit).cloned().collect();
87 (!facts.is_empty()).then_some(facts)
88 }
89
90 fn declaration_source_occurrences(
91 &self,
92 token: QueryToken<'_>,
93 unit: &CodeUnit,
94 ) -> Option<Vec<crate::source_facts::CppDeclarationOccurrence>> {
95 let source = self.declaration_source_facts(token, unit.source())?;
96 let occurrences = source.declaration_occurrences(unit);
97 (!occurrences.is_empty()).then_some(occurrences)
98 }
99
100 /// Navigation alternatives come from the same canonical occurrences as
101 /// declaration properties. An analyzer that selects alternate dialects must
102 /// override this method to join against the selected dialect's own arena.
103 fn declaration_navigation_occurrences(
104 &self,
105 token: QueryToken<'_>,
106 unit: &CodeUnit,
107 ) -> Option<Vec<crate::source_facts::CppNavigationOccurrence>> {
108 let source = self.declaration_source_facts(token, unit.source())?;
109 let facts = self.declaration_source_properties(token, unit)?;
110 Some(
111 facts
112 .into_iter()
113 .map(|fact| source.navigation_occurrence(&fact))
114 .collect(),
115 )
116 }
117
118 /// Structured includes for a disposable visibility traversal.
119 fn visibility_import_statements(
120 &self,
121 token: QueryToken<'_>,
122 file: &ProjectFile,
123 ) -> Vec<String> {
124 self.declaration_source_facts(token, file)
125 .map(|source| canonical_include_statements(&source))
126 .unwrap_or_default()
127 }
128
129 /// Physical identifier candidates used only to discover source files for
130 /// a bounded visibility traversal. Re-keyed out-of-line definitions do not
131 /// add an includable source, so analyzer implementations may answer this
132 /// from their stored declaration index without global identity
133 /// reconciliation.
134 fn visibility_identifier_candidates(&self, identifier: &str) -> BTreeSet<CodeUnit> {
135 self.lookup_candidates_by_identifier(identifier)
136 }
137
138 /// Batched form of [`Self::visibility_identifier_candidates`].
139 fn visibility_identifier_candidates_batch(
140 &self,
141 identifiers: &HashSet<String>,
142 cancellation: Option<&CancellationToken>,
143 ) -> HashMap<String, BTreeSet<CodeUnit>> {
144 identifiers
145 .iter()
146 .take_while(|_| !cancellation.is_some_and(CancellationToken::is_cancelled))
147 .map(|identifier| {
148 (
149 identifier.clone(),
150 self.visibility_identifier_candidates(identifier),
151 )
152 })
153 .collect()
154 }
155
156 /// The callable role recorded for a physical stored declaration, without
157 /// consulting reconciliation fallbacks that may themselves be building.
158 fn stored_callable_unit_role(&self, callable: &CodeUnit) -> CppCallableUnitRole;
159
160 /// The physical signature rows for one stored declaration, without
161 /// resolution-time reconciliation. Linkage and arity are stored facts;
162 /// callers that need those facts must not rebuild the visibility joins
163 /// used to decorate an out-of-line member's metadata.
164 fn stored_signature_metadata(&self, callable: &CodeUnit) -> Vec<SignatureMetadata> {
165 self.signature_metadata(callable)
166 }
167
168 /// The workspace-wide `#include` resolution table, built once per analyzer
169 /// generation from [`IncludeTargetIndex::build`].
170 fn include_target_index(&self) -> &IncludeTargetIndex;
171
172 /// Every class-like or alias declaration reachable from `file` through its
173 /// `#include` closure, memoized per file. See this module's note.
174 fn visible_type_units(&self, file: &ProjectFile) -> Arc<Vec<CodeUnit>>;
175
176 /// [`Self::visible_type_units`] under a caller's deadline.
177 ///
178 /// `None` means the include-closure walk stopped short. Nothing is
179 /// memoized in that case: a truncated class table is indistinguishable
180 /// from a file that simply sees fewer types, so every later base-specifier
181 /// resolution reading it would silently lose ancestors.
182 ///
183 /// This is the shape issue #1748 needed. The closure walk is individually
184 /// cheap -- a fraction of a millisecond to about 180 ms -- but the
185 /// descendant-index build above it runs one per class in the workspace,
186 /// which on a large tree is tens of thousands of them inside a single
187 /// request that asked for thirty seconds.
188 fn visible_type_units_while(
189 &self,
190 file: &ProjectFile,
191 keep_going: &dyn Fn() -> bool,
192 ) -> Option<Arc<Vec<CodeUnit>>>;
193
194 /// The per-file structured using index (ordinary using declarations and
195 /// using-directives with their guard environments), memoized per file.
196 /// Built by [`crate::graph::extractor::build_source_using_index`], which is
197 /// a pure function of the file's parsed content.
198 ///
199 /// Memoized on the analyzer rather than on `VisibilityIndex` because a
200 /// fresh visibility index is built per usage query: rebuilding the index
201 /// per query re-walked a 9.5 MB amalgamation's AST once per candidate
202 /// (issue #1927).
203 fn source_using_index(
204 &self,
205 token: QueryToken<'_>,
206 file: &ProjectFile,
207 ) -> Arc<SourceUsingIndex>;
208
209 /// The indexed source of `file` (`TreeSitterAnalyzer::file_source`).
210 fn file_source(&self, file: &ProjectFile) -> Option<String>;
211
212 /// The parsed tree and its source backing for `file`, from the analyzer's
213 /// query read cache.
214 ///
215 /// The single hottest member of this trait: the usage graph reaches it at
216 /// 27 call sites. The cache is *not* rebuilt per call -- `VisibilityIndex`
217 /// borrows the analyzer rather than cloning it precisely so this stays warm
218 /// across a scan (#1175), so an implementor must forward to the same
219 /// analyzer the query is running against.
220 ///
221 /// The [`QueryToken`] is proof that a request scope is open, so the cache
222 /// this reads is live (issue #2414 step 3).
223 fn prepared_syntax(
224 &self,
225 token: QueryToken<'_>,
226 file: &ProjectFile,
227 ) -> Option<Arc<PreparedSyntaxTree>>;
228
229 /// The persisted linkage fact for one C++ field, when the parser recorded
230 /// it. A missing fact is unavailable linkage evidence.
231 fn cpp_field_linkage(&self, code_unit: &CodeUnit) -> Option<CppFieldLinkage>;
232
233 /// The cached result of a preprocessor-visible include-reachability walk.
234 ///
235 /// The reference language and the source-only language proof affect
236 /// `__cplusplus` guards. The reference root identifies those facts within
237 /// one immutable analyzer generation; the proof stays lazy on cache hits.
238 fn cached_unconditional_include_reachability(
239 &self,
240 first: &ProjectFile,
241 donor_source: &ProjectFile,
242 reference_file: &ProjectFile,
243 ) -> Option<bool>;
244
245 /// Store a completed preprocessor-visible include-reachability walk.
246 fn cache_unconditional_include_reachability(
247 &self,
248 first: &ProjectFile,
249 donor_source: &ProjectFile,
250 reference_file: &ProjectFile,
251 reaches: bool,
252 );
253
254 /// The file's embedded export-macro class recovery, resolved once per file.
255 ///
256 /// Built by [`crate::declarations::CppRecoveredExportClassIndex::build`],
257 /// which is a pure function of the file's parsed content. Memoized on the
258 /// analyzer for the same reason as [`Self::source_using_index`]: the
259 /// declaration-strength question asks it once per class-like unit, and
260 /// re-deriving it walks and sorts every `ERROR` subtree in the file (#1496).
261 fn recovered_export_class_index(
262 &self,
263 token: QueryToken<'_>,
264 file: &ProjectFile,
265 ) -> Arc<CppRecoveredExportClassIndex>;
266
267 /// The namespaces C++ parse recovery dropped from `file`'s tree, resolved
268 /// once per file.
269 ///
270 /// Built by [`OrphanedNamespaceScopeIndex::build`], a pure function of the
271 /// file's parsed content, and empty for a file without parse errors. Both
272 /// lookup directions derive every lexical scope in the file through it, so
273 /// it is memoized on the analyzer like [`Self::source_using_index`] rather
274 /// than rebuilt per query or per reference (issue #1537).
275 fn orphaned_namespace_scopes(
276 &self,
277 token: QueryToken<'_>,
278 file: &ProjectFile,
279 ) -> Arc<OrphanedNamespaceScopeIndex>;
280
281 /// The memoized answer of
282 /// [`crate::graph::resolver::cpp_class_declaration_strength`] for one
283 /// class-like unit, when a previous ask stored it.
284 ///
285 /// The answer is a pure function of the unit's declaration ranges and its
286 /// file's parse tree, so it is stable for an analyzer generation. Memoized
287 /// on the analyzer for the same reason as [`Self::source_using_index`]: the
288 /// inverse scan asks it once per declaration seed, and on a translation
289 /// unit the parser could not fully recover each ask re-derives the
290 /// export-macro recovery shapes from the file's `ERROR` subtrees, which is
291 /// quadratic in the file's size (#1496).
292 fn cached_class_declaration_strength(
293 &self,
294 candidate: &CodeUnit,
295 ) -> Option<CppClassDeclarationStrength>;
296
297 /// Store a completed declaration-strength answer.
298 fn cache_class_declaration_strength(
299 &self,
300 candidate: &CodeUnit,
301 strength: CppClassDeclarationStrength,
302 );
303
304 /// The declaration's syntactic owner, which unlike
305 /// [`CodeUnitIndex::parent_of`] never falls back to a definition-row lookup.
306 fn structural_parent_of(&self, code_unit: &CodeUnit) -> Option<CodeUnit>;
307
308 /// The persisted C++ template metadata side table's row for `code_unit`.
309 fn template_metadata(&self, code_unit: &CodeUnit) -> Option<CppTemplateMetadata>;
310
311 /// Whether a reference written in the header `file` reads the declarations
312 /// it can see with C semantics: every workspace translation unit that
313 /// provably compiles this header compiles it as C (issue #1970).
314 ///
315 /// Always false for a translation unit -- its own extension settles its
316 /// dialect, which [`crate::graph::resolver::is_c_source_file`] answers
317 /// without asking the analyzer. Both halves are combined by
318 /// [`crate::graph::resolver::reference_uses_c_semantics`], the one helper
319 /// resolution asks.
320 ///
321 /// A header both languages provably include reports false: forward
322 /// resolution from it reports the C++ identity, and the site-equivalence
323 /// union below is what keeps inverse in agreement.
324 fn header_uses_c_semantics(&self, file: &ProjectFile) -> bool;
325
326 /// The declarations of `file` as one of its two readings sees them.
327 ///
328 /// `c_semantics` false is the C++ reading, which is exactly
329 /// [`CodeUnitIndex::declarations`]. True is the C reading: the stored
330 /// `cpp:c` row-set when the blob has one, and otherwise the same C++
331 /// row-set, because "no C rows" means the two readings agree.
332 ///
333 /// Candidate enumeration selects a reading here and nowhere else: include
334 /// activation, preprocessor-guard compatibility, block-scope shadowing and
335 /// ambiguity all run unchanged over whichever set comes back.
336 fn declarations_in_reading(&self, file: &ProjectFile, c_semantics: bool) -> BTreeSet<CodeUnit>;
337
338 /// The identities of the other reading that share `code_unit`'s
339 /// declaration site -- the same source file and the same declaration byte
340 /// range -- empty when the two readings agree about it.
341 ///
342 /// Keyed on the range, never on a name. Inverse results are unioned across
343 /// these so a query against either identity of one declaration reports
344 /// every reference found under both readings.
345 fn site_equivalent_units(&self, code_unit: &CodeUnit) -> Vec<CodeUnit>;
346
347 /// Every distinct `compile_commands.json` configuration governing `file`,
348 /// empty when the workspace has no compile database entry naming it. The
349 /// only analyzer-resident product [`crate::diagnostics`] needs.
350 ///
351 /// A file the build compiles in several configurations yields several
352 /// contexts, because their include closures can disagree about a name.
353 fn compile_contexts_for(&self, file: &ProjectFile) -> &[CppCompileContext];
354
355 /// Every workspace translation unit whose `#include` closure transitively
356 /// reaches `file` -- the header-to-TU attribution map from #1970's
357 /// Milestone 2, which #2011 phase 2 reads for header-sited guard proof.
358 /// Empty when nothing reaches `file` or the implementor has no include
359 /// graph, which conservatively yields no compile-context facts.
360 fn reaching_translation_units(&self, _file: &ProjectFile) -> Vec<ProjectFile> {
361 Vec::new()
362 }
363
364 /// Count a precise-parent resolution against the analyzer's counter.
365 ///
366 /// Called from production code in [`crate::graph::resolver`], which is why
367 /// it is on the trait at all; the counter itself stays on the analyzer.
368 ///
369 /// The default is a no-op because the two gates are not the same gate:
370 /// Cargo turns this crate's `test-support` on for the whole build graph
371 /// whenever `brokk-bifrost-analysis`'s dev-dependencies are in play, while
372 /// the analyzer-side counter field is `#[cfg(any(test, feature =
373 /// "test-support"))]` on *that* crate. The implementor overrides this
374 /// exactly when it has a counter to record into -- which is the build the
375 /// tests reading the counter run in.
376 #[cfg(any(test, feature = "test-support"))]
377 fn record_cpp_parent_resolution_for_test(&self) {}
378
379 /// Count a class-declaration-strength parse. See
380 /// [`Self::record_cpp_parent_resolution_for_test`].
381 #[cfg(any(test, feature = "test-support"))]
382 fn record_cpp_class_strength_parse_for_test(&self) {}
383
384 /// Count a guard-ancestry inspection during a per-file using-index build.
385 /// See [`Self::record_cpp_parent_resolution_for_test`].
386 #[cfg(any(test, feature = "test-support"))]
387 fn record_using_guard_context_inspection_for_test(&self) {}
388}