lean_ctx_ext/core/repomap/
graph.rs1use std::collections::{HashMap, HashSet};
8
9use crate::core::call_graph::{CallGraph, CallGraphInputs};
10use crate::core::graph_index::{self, ProjectIndex, SymbolEntry};
11
12#[derive(Debug, Clone)]
14pub struct SymbolDef {
15 pub name: String,
16 pub kind: String,
17 pub file: String,
18 pub line: usize,
19 pub end_line: usize,
20 pub is_exported: bool,
21 pub signature: String,
22}
23
24pub struct RepoGraph {
26 pub files: HashSet<String>,
27 pub forward: HashMap<String, Vec<String>>,
29 pub symbols_by_file: HashMap<String, Vec<SymbolDef>>,
31}
32
33impl RepoGraph {
34 pub fn build(project_root: &str) -> Self {
39 let (index, content_cache) = graph_index::scan_with_content_cache(project_root);
40 let calls = graph_call_pairs(project_root).unwrap_or_else(|| {
41 let cg_inputs = CallGraphInputs::from_project_index(&index);
42 let call_graph = CallGraph::load_or_build(project_root, &cg_inputs);
43 structural_call_pairs(&cg_inputs, &call_graph)
44 });
45
46 Self::from_index_and_calls(&index, &calls, &content_cache)
47 }
48
49 fn from_index_and_calls(
51 index: &ProjectIndex,
52 calls: &[(String, String)],
53 content_cache: &HashMap<String, String>,
54 ) -> Self {
55 let files: HashSet<String> = index.files.keys().cloned().collect();
56
57 let mut forward: HashMap<String, Vec<String>> = HashMap::new();
58
59 for edge in &index.edges {
61 if files.contains(&edge.from) && files.contains(&edge.to) && edge.from != edge.to {
62 forward
63 .entry(edge.from.clone())
64 .or_default()
65 .push(edge.to.clone());
66 }
67 }
68
69 for (from, to) in calls {
71 if files.contains(from) && files.contains(to) && from != to {
72 forward.entry(from.clone()).or_default().push(to.clone());
73 }
74 }
75
76 for deps in forward.values_mut() {
78 deps.sort();
79 deps.dedup();
80 }
81
82 let symbols_by_file = build_symbols_with_signatures(index, content_cache);
83
84 Self {
85 files,
86 forward,
87 symbols_by_file,
88 }
89 }
90}
91
92fn graph_call_pairs(project_root: &str) -> Option<Vec<(String, String)>> {
100 use crate::core::property_graph::{CodeGraph, EdgeKind};
101 if crate::core::property_graph::engine_outdated(project_root) {
102 return None;
103 }
104 let graph = CodeGraph::open(project_root).ok()?;
105 let pairs: Vec<(String, String)> = graph
106 .file_edges_of_kind(&EdgeKind::Calls)
107 .ok()?
108 .into_iter()
109 .filter(|(from, to, _)| graph.serves_file(from) && graph.serves_file(to))
112 .map(|(from, to, _)| (from, to))
113 .collect();
114 (!pairs.is_empty() || graph.has_semantic_answers().unwrap_or(false)).then_some(pairs)
115}
116
117fn structural_call_pairs(
121 inputs: &CallGraphInputs,
122 call_graph: &CallGraph,
123) -> Vec<(String, String)> {
124 crate::core::call_graph::resolve_edge_callee_files(inputs, &call_graph.edges)
125 .into_iter()
126 .zip(&call_graph.edges)
127 .filter_map(|(to, edge)| Some((edge.caller_file.clone(), to?)))
128 .collect()
129}
130
131fn build_symbols_with_signatures(
133 index: &ProjectIndex,
134 content_cache: &HashMap<String, String>,
135) -> HashMap<String, Vec<SymbolDef>> {
136 let mut result: HashMap<String, Vec<SymbolDef>> = HashMap::new();
137
138 let mut idx_symbols: HashMap<&str, Vec<&SymbolEntry>> = HashMap::new();
140 for sym in index.symbols.values() {
141 idx_symbols.entry(sym.file.as_str()).or_default().push(sym);
142 }
143
144 for (file_path, file_entry) in &index.files {
145 let ext = std::path::Path::new(file_path)
146 .extension()
147 .and_then(|e| e.to_str())
148 .unwrap_or("");
149
150 let signatures = content_cache
152 .get(file_path)
153 .map(|content| crate::core::signatures::extract_signatures(content, ext))
154 .unwrap_or_default();
155
156 let sig_by_name: HashMap<&str, &crate::core::signatures::Signature> =
157 signatures.iter().map(|s| (s.name.as_str(), s)).collect();
158
159 let mut file_symbols: Vec<SymbolDef> = Vec::new();
160
161 if let Some(syms) = idx_symbols.get(file_path.as_str()) {
162 for sym in syms {
163 let signature = sig_by_name
164 .get(sym.name.as_str())
165 .map_or_else(|| format!("{} {}", sym.kind, sym.name), |s| s.to_compact());
166
167 file_symbols.push(SymbolDef {
168 name: sym.name.clone(),
169 kind: sym.kind.clone(),
170 file: sym.file.clone(),
171 line: sym.start_line,
172 end_line: sym.end_line,
173 is_exported: sym.is_exported,
174 signature,
175 });
176 }
177 }
178
179 for export in &file_entry.exports {
181 let already_present = file_symbols.iter().any(|s| s.name == *export);
182 if !already_present {
183 let signature = sig_by_name
184 .get(export.as_str())
185 .map_or_else(|| export.clone(), |s| s.to_compact());
186
187 let (line, end_line) = sig_by_name
188 .get(export.as_str())
189 .and_then(|s| s.start_line.zip(s.end_line))
190 .unwrap_or((0, 0));
191
192 file_symbols.push(SymbolDef {
193 name: export.clone(),
194 kind: "export".to_string(),
195 file: file_path.clone(),
196 line,
197 end_line,
198 is_exported: true,
199 signature,
200 });
201 }
202 }
203
204 file_symbols.sort_by_key(|s| s.line);
205
206 if !file_symbols.is_empty() {
207 result.insert(file_path.clone(), file_symbols);
208 }
209 }
210
211 result
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217
218 #[test]
222 fn ambiguous_calls_are_not_linked_by_name() {
223 use crate::core::call_graph::{CallEdge, SymbolSpan};
224 let span = |file: &str, name: &str| SymbolSpan {
225 file: file.into(),
226 name: name.into(),
227 start_line: 1,
228 end_line: 3,
229 kind: "fn".into(),
230 };
231 let inputs = CallGraphInputs {
232 project_root: "/tmp".into(),
233 file_paths: vec!["a.rs".into(), "b.rs".into(), "app.rs".into()],
234 symbols: vec![
235 span("a.rs", "save"),
236 span("b.rs", "save"),
237 span("b.rs", "load"),
238 ],
239 import_edges: Vec::new(),
240 };
241 let call = |callee: &str| CallEdge {
242 caller_file: "app.rs".into(),
243 caller_symbol: "run".into(),
244 caller_line: 2,
245 callee_name: callee.into(),
246 ..Default::default()
247 };
248 let mut call_graph = CallGraph::new("/tmp");
249 call_graph.edges = vec![call("save"), call("load")];
250
251 assert_eq!(
252 structural_call_pairs(&inputs, &call_graph),
253 [("app.rs".to_string(), "b.rs".to_string())],
254 "only the unique `load` binds"
255 );
256 }
257
258 #[test]
261 fn empty_graph_calls_count_only_after_a_semantic_answer() {
262 use crate::core::property_graph::{
263 CachedResolution, CodeGraph, GRAPH_ENGINE_VERSION, PropertyGraphMetaV1, write_meta,
264 };
265 let _iso = crate::core::data_dir::isolated_data_dir();
266 let proj = tempfile::tempdir().unwrap();
267 let root = proj.path().to_str().unwrap();
268 let meta = PropertyGraphMetaV1 {
269 built_at: "2026-01-01T00:00:00Z".to_string(),
270 engine_version: GRAPH_ENGINE_VERSION,
271 ..Default::default()
272 };
273 write_meta(root, &meta).unwrap();
274 let graph = CodeGraph::open(root).unwrap();
275 assert_eq!(graph_call_pairs(root), None, "not consolidated yet");
276
277 let veto = CachedResolution {
278 backend: "lsp:test@1".into(),
279 outcome: "external".into(),
280 target_file: None,
281 target_line: None,
282 target_symbol: None,
283 context: String::new(),
284 };
285 let admission = crate::core::context_admission::stores::StoreAdmission::current();
286 graph
287 .semantic_store(("app.rs", 2, 4, "definition"), "h", &veto, &admission)
288 .unwrap();
289 assert_eq!(graph_call_pairs(root), Some(Vec::new()), "vetoed stays out");
290 }
291
292 #[test]
293 fn repo_graph_deduplicates_edges() {
294 let mut index = ProjectIndex::new("/tmp");
295 index.files.insert("a.rs".into(), dummy_file_entry("a.rs"));
296 index.files.insert("b.rs".into(), dummy_file_entry("b.rs"));
297 index.edges.push(graph_index::IndexEdge {
298 from: "a.rs".into(),
299 to: "b.rs".into(),
300 kind: "import".into(),
301 weight: 1.0,
302 });
303 index.edges.push(graph_index::IndexEdge {
304 from: "a.rs".into(),
305 to: "b.rs".into(),
306 kind: "import".into(),
307 weight: 1.0,
308 });
309
310 let graph = RepoGraph::from_index_and_calls(&index, &[], &HashMap::new());
311
312 let a_deps = graph.forward.get("a.rs").unwrap();
313 assert_eq!(a_deps.len(), 1, "duplicate edges should be deduped");
314 }
315
316 #[test]
317 fn repo_graph_ignores_self_edges() {
318 let mut index = ProjectIndex::new("/tmp");
319 index.files.insert("a.rs".into(), dummy_file_entry("a.rs"));
320 index.edges.push(graph_index::IndexEdge {
321 from: "a.rs".into(),
322 to: "a.rs".into(),
323 kind: "import".into(),
324 weight: 1.0,
325 });
326
327 let graph = RepoGraph::from_index_and_calls(&index, &[], &HashMap::new());
328
329 assert!(
330 !graph.forward.contains_key("a.rs"),
331 "self-edges should be excluded"
332 );
333 }
334
335 fn dummy_file_entry(path: &str) -> graph_index::FileEntry {
336 graph_index::FileEntry {
337 path: path.into(),
338 hash: "abc".into(),
339 language: "rust".into(),
340 line_count: 10,
341 token_count: 50,
342 exports: vec![],
343 summary: String::new(),
344 }
345 }
346}