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