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