Skip to main content

brokk_bifrost_cpp/graph/
mod.rs

1//! The C++ usage graph's language knowledge.
2//!
3//! The forward scan ([`extractor`] plus [`hits`]), the visibility/macro/include
4//! resolver ([`resolver`]) and the whole-workspace inverted per-file walk
5//! ([`inverted`]) are one body of code and crossed together: `extractor` glob
6//! imports `resolver`, `hits` reads `extractor`'s scan context, and `inverted`
7//! names forty items from the other two.
8//!
9//! No analyzer handle appears here. `brokk-bifrost-analysis` downcasts once and
10//! hands over a [`CppGraphSource`] -- the *dispatching* analyzer's side of a
11//! scan -- which carries the [`CppSource`] the memoized C++ products
12//! come from.
13
14pub mod extractor;
15pub mod hits;
16pub mod inverted;
17mod macro_lexical;
18pub mod resolver;
19pub mod syntax;
20
21use crate::graph_support::CppSource;
22use brokk_bifrost_core::analyzer::capabilities::{TypeAliasProvider, TypeHierarchyProvider};
23use brokk_bifrost_core::analyzer::fq_name::FqName;
24use brokk_bifrost_core::analyzer::model::{CppFieldLinkage, SignatureMetadata};
25use brokk_bifrost_core::analyzer::query_token::QueryToken;
26use brokk_bifrost_core::analyzer::{CodeUnit, CodeUnitIndex, ProjectFile, Range};
27use std::collections::BTreeSet;
28
29/// The workspace-wide questions a C++ scan asks of the *dispatching* analyzer
30/// rather than of the C++ analyzer.
31///
32/// `import_statements` is `IAnalyzer`'s raw `#include` lines. Definition reads
33/// also stay the dispatching analyzer's job: the language crate can issue the
34/// core relational request but cannot own SQLite, and a mixed workspace must
35/// coordinate its language-local snapshots through `MultiAnalyzer`.
36pub trait CppWorkspaceSource {
37    /// The raw import (`#include`) lines recorded for `file`.
38    fn import_statements(&self, file: &ProjectFile) -> Vec<String>;
39
40    /// Exact lookup for a name already carried as extractor-owned segments.
41    /// Results are owned because the relational store, not a generation-wide
42    /// Rust map, owns the rows.
43    fn definitions_by_name(&self, token: QueryToken<'_>, name: &FqName) -> Vec<CodeUnit>;
44
45    /// Identifier-bounded candidates for a structurally segmented source path
46    /// whose intermediate kinds are not known until resolution.
47    fn definitions_by_identifier(&self, token: QueryToken<'_>, name: &FqName) -> Vec<CodeUnit>;
48}
49
50/// The workspace definition query surface, spelled so the C++ resolver does
51/// not depend on the analysis crate's store implementation.
52///
53/// Carries the request scope's [`QueryToken`] alongside the source, so a
54/// lookup made through it is proof-carrying without every C++ call site
55/// re-threading the token (issue #2423 milestone B).
56#[derive(Clone, Copy)]
57pub struct CppWorkspaceDefinitions<'a>(&'a dyn CppWorkspaceSource, QueryToken<'a>);
58
59impl<'a> CppWorkspaceDefinitions<'a> {
60    pub fn exact(&self, name: &FqName) -> Vec<CodeUnit> {
61        self.0.definitions_by_name(self.1, name)
62    }
63
64    pub fn identifier(&self, name: &FqName) -> Vec<CodeUnit> {
65        self.0.definitions_by_identifier(self.1, name)
66    }
67}
68
69/// The *dispatching* analyzer's side of a C++ usage-graph scan.
70///
71/// Deliberately not the C++ analyzer, for the reason recorded on
72/// `PythonGraphSource` and `CSharpGraphSource`: in a mixed workspace the query
73/// is issued against a `MultiAnalyzer`, whose `definitions` merges every
74/// language's shards and whose provider accessors cross language boundaries.
75/// The C++ analyzer that answers the C++-only questions rides along in
76/// [`Self::cpp`], resolved once by the shim's `resolve_analyzer::<CppAnalyzer>`
77/// downcast instead of once per call site as before the move; `None` is the
78/// same answer that downcast's `else` arm gave.
79#[derive(Clone, Copy)]
80pub struct CppGraphSource<'a> {
81    pub index: &'a dyn CodeUnitIndex,
82    pub cpp: Option<&'a dyn CppSource>,
83    pub aliases: Option<&'a dyn TypeAliasProvider>,
84    pub hierarchy: Option<&'a dyn TypeHierarchyProvider>,
85    pub workspace: &'a dyn CppWorkspaceSource,
86    /// Proof that the request scope this bundle serves is open. The bundle is
87    /// a per-query object built at a query boundary, so the syntax accessors
88    /// its resolution paths reach can take the proof from here rather than
89    /// from ninety extra parameters (issue #2414 step 3).
90    pub token: QueryToken<'a>,
91}
92
93impl<'a> CppGraphSource<'a> {
94    /// The C++ source standing in for the dispatching analyzer.
95    ///
96    /// For the four resolution paths that only ever had the concrete C++
97    /// analyzer in hand: they passed `&CppAnalyzer` where a `&dyn IAnalyzer`
98    /// was wanted, and its `type_alias_provider()`/`type_hierarchy_provider()`
99    /// both answered `Some(self)`, so every field is the same object here too.
100    pub fn from_source(source: &'a dyn CppSource, token: QueryToken<'a>) -> Self {
101        Self {
102            index: source,
103            cpp: Some(source),
104            aliases: Some(source),
105            hierarchy: Some(source),
106            workspace: source,
107            token,
108        }
109    }
110
111    pub fn type_alias_provider(&self) -> Option<&'a dyn TypeAliasProvider> {
112        self.aliases
113    }
114
115    pub fn type_hierarchy_provider(&self) -> Option<&'a dyn TypeHierarchyProvider> {
116        self.hierarchy
117    }
118
119    pub fn import_statements(&self, file: &ProjectFile) -> Vec<String> {
120        self.workspace.import_statements(file)
121    }
122
123    /// Canonical AST-owned include paths for the file's primary reading.
124    /// `None` means the source-facts mount is unavailable.
125    pub fn canonical_include_paths(&self, file: &ProjectFile) -> Option<Vec<String>> {
126        self.cpp?.canonical_include_paths(self.token, file)
127    }
128
129    pub fn workspace_definitions(&self) -> CppWorkspaceDefinitions<'a> {
130        CppWorkspaceDefinitions(self.workspace, self.token)
131    }
132
133    pub fn parent_of(&self, code_unit: &CodeUnit) -> Option<CodeUnit> {
134        self.index.parent_of(code_unit)
135    }
136
137    pub fn ranges(&self, code_unit: &CodeUnit) -> Vec<Range> {
138        self.index.ranges(code_unit)
139    }
140
141    pub fn enclosing_code_unit(&self, file: &ProjectFile, range: &Range) -> Option<CodeUnit> {
142        self.index.enclosing_code_unit(file, range)
143    }
144
145    pub fn declaration_source_occurrences(
146        &self,
147        unit: &CodeUnit,
148    ) -> Option<Vec<crate::source_facts::CppDeclarationOccurrence>> {
149        self.cpp?.declaration_source_occurrences(self.token, unit)
150    }
151
152    pub fn declaration_source_properties(
153        &self,
154        unit: &CodeUnit,
155    ) -> Option<Vec<brokk_bifrost_core::analyzer::cpp_facts::CppDeclarationSourceFact>> {
156        self.cpp?.declaration_source_properties(self.token, unit)
157    }
158
159    pub fn signature_metadata(&self, code_unit: &CodeUnit) -> Vec<SignatureMetadata> {
160        self.index.signature_metadata(code_unit)
161    }
162
163    pub fn cpp_field_linkage(&self, code_unit: &CodeUnit) -> Option<CppFieldLinkage> {
164        self.cpp?.cpp_field_linkage(code_unit)
165    }
166
167    pub fn signatures(&self, code_unit: &CodeUnit) -> Vec<String> {
168        self.index.signatures(code_unit)
169    }
170
171    pub fn get_source(&self, code_unit: &CodeUnit, include_comments: bool) -> Option<String> {
172        self.index.get_source(code_unit, include_comments)
173    }
174
175    pub fn indexed_source(&self, file: &ProjectFile) -> Option<String> {
176        self.index.indexed_source(file)
177    }
178
179    pub fn declarations(&self, file: &ProjectFile) -> BTreeSet<CodeUnit> {
180        self.index.declarations(file)
181    }
182
183    /// Whether a reference written in `file` reads C++ source with C semantics
184    /// (issue #1970). Without a C++ analyzer behind this source only the path
185    /// evidence is available, which is exactly what
186    /// [`resolver::is_c_source_file`] answered before headers gained a second
187    /// reading.
188    pub fn reference_uses_c_semantics(&self, file: &ProjectFile) -> bool {
189        match self.cpp {
190            Some(cpp) => resolver::reference_uses_c_semantics(cpp, file),
191            None => resolver::is_c_source_file(file),
192        }
193    }
194
195    /// [`crate::graph_support::CppSource::declarations_in_reading`], falling
196    /// back to the single reading a bare index can serve.
197    pub fn declarations_in_reading(
198        &self,
199        file: &ProjectFile,
200        c_semantics: bool,
201    ) -> BTreeSet<CodeUnit> {
202        match self.cpp {
203            Some(cpp) if c_semantics => cpp.declarations_in_reading(file, true),
204            _ => self.index.declarations(file),
205        }
206    }
207
208    /// [`crate::graph_support::CppSource::site_equivalent_units`], empty
209    /// without a C++ analyzer.
210    pub fn site_equivalent_units(&self, code_unit: &CodeUnit) -> Vec<CodeUnit> {
211        match self.cpp {
212            Some(cpp) => cpp.site_equivalent_units(code_unit),
213            None => Vec::new(),
214        }
215    }
216
217    pub fn direct_children(&self, code_unit: &CodeUnit) -> Vec<CodeUnit> {
218        self.index.direct_children(code_unit)
219    }
220
221    pub fn definitions(&self, fq_name: &str) -> Box<dyn Iterator<Item = CodeUnit> + '_> {
222        self.index.definitions(fq_name)
223    }
224}
225
226/// [`crate::identity::cpp_callable_definitions_share_identity_evidence`] with
227/// its header/implementation evidence root supplied from the graph source.
228///
229/// The searchtools consumers reach the same predicate through the shim wrapper
230/// that owns the `resolve_analyzer` downcast; the scan already holds the
231/// resolved C++ source, so it passes the include index in directly. A source
232/// without a C++ analyzer answers `false`, exactly as the downcast's `else` arm
233/// did.
234pub fn callable_definitions_share_identity_evidence(
235    analyzer: &CppGraphSource<'_>,
236    left: &CodeUnit,
237    right: &CodeUnit,
238) -> bool {
239    crate::identity::cpp_callable_definitions_share_identity_evidence(
240        analyzer.index,
241        left,
242        right,
243        |left_source, right_source| {
244            let Some(cpp) = analyzer.cpp else {
245                return false;
246            };
247            crate::identity::cpp_header_body_files_are_related(
248                cpp,
249                analyzer.token,
250                left_source,
251                right_source,
252            )
253        },
254    )
255}
256
257/// The structured-parameter variant of
258/// [`callable_definitions_share_identity_evidence`].
259///
260/// Use this when the two declarations may differ in non-identity parameter
261/// syntax, such as a default argument written only on the header prototype.
262pub fn callable_definitions_share_identity_evidence_with_visibility(
263    analyzer: &CppGraphSource<'_>,
264    visibility: &resolver::VisibilityIndex<'_>,
265    left: &CodeUnit,
266    right: &CodeUnit,
267) -> bool {
268    crate::identity::cpp_callable_definitions_share_identity_evidence_with_visibility(
269        analyzer,
270        visibility,
271        left,
272        right,
273        |left_source, right_source| {
274            let Some(cpp) = analyzer.cpp else {
275                return false;
276            };
277            crate::identity::cpp_header_body_files_are_related(
278                cpp,
279                analyzer.token,
280                left_source,
281                right_source,
282            )
283        },
284    )
285}