use std::collections::HashMap; use std::path::Path; use chrono::Utc; use compliance_core::error::CoreError; use compliance_core::models::graph::{ CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, }; use compliance_core::traits::graph_builder::ParseOutput; use petgraph::graph::{DiGraph, NodeIndex}; use tracing::info; use crate::parsers::registry::ParserRegistry; use super::community::apply_communities; use super::impact::ImpactAnalyzer; /// Walk up the qualified-name hierarchy to find the closest ancestor /// that exists in the node map. /// /// For `"src/main.rs::config::load"` this tries: /// 1. `"src/main.rs::config"` (trim last `::` segment) /// 2. `"src/main.rs"` (trim again) /// /// Returns the first match found, or `None` if the node is a root. fn find_parent_qname(qname: &str, node_map: &HashMap) -> Option { let mut current = qname.to_string(); loop { // Try stripping the last "::" segment if let Some(pos) = current.rfind("::") { current.truncate(pos); if node_map.contains_key(¤t) { return Some(current); } continue; } // No more "::" — this is a top-level node (file), no parent return None; } } /// The last segment of a qualified name or edge target, after the last /// `::` and then the last `.`: `src/a.py::Cls.run` and `self.run` both end /// in `run`. Every name a target can match by suffix shares the target's /// last segment, so it is the key the candidates are found by. fn last_segment(name: &str) -> &str { let after_path = name.rsplit("::").next().unwrap_or(name); after_path.rsplit('.').next().unwrap_or(after_path) } /// One node an edge target may resolve to. struct Candidate<'a> { qualified: &'a str, file_path: &'a str, idx: NodeIndex, } /// Resolves edge targets to nodes. Candidates are found by the target's /// last segment instead of scanning every node per edge, and when several /// match, the one in the edge's own file wins (C's `static` functions, /// same-named helpers), then the first by qualified name, so a rebuild /// links the same way every time. struct NameIndex<'a> { exact: &'a HashMap, by_last: HashMap<&'a str, Vec>>, /// File nodes by file name, for `#include "uart.h"` and other targets /// that are paths. files_by_name: HashMap<&'a str, Vec>>, } impl<'a> NameIndex<'a> { fn new(nodes: &'a [CodeNode], exact: &'a HashMap) -> Self { let mut by_last: HashMap<&str, Vec>> = HashMap::new(); let mut files_by_name: HashMap<&str, Vec>> = HashMap::new(); for node in nodes { let Some(&idx) = exact.get(&node.qualified_name) else { continue; }; let candidate = || Candidate { qualified: &node.qualified_name, file_path: &node.file_path, idx, }; by_last .entry(last_segment(&node.qualified_name)) .or_default() .push(candidate()); if matches!(node.kind, CodeNodeKind::File) { let name = node.qualified_name.rsplit('/').next().unwrap_or_default(); files_by_name.entry(name).or_default().push(candidate()); } } for list in by_last.values_mut().chain(files_by_name.values_mut()) { list.sort_unstable_by(|a, b| a.qualified.cmp(b.qualified)); } Self { exact, by_last, files_by_name, } } /// The node `target` names, seen from an edge in `from_file`. /// /// Resolution strategies (in order): /// 1. Direct qualified-name match /// 2. Suffix match: "foo" matches "src/main.rs::mod::foo" and "src/app.js.foo" /// 3. Module-path match: "crate::config::load" matches "src/config.rs::load" /// 4. Self-method: "self.method" matches "::method" /// 5. File path: "uart.h" and "./lib/uart.h" match the file "src/lib/uart.h" fn resolve(&self, target: &str, from_file: &str) -> Option { if let Some(&idx) = self.exact.get(target) { return Some(idx); } let candidates = self.by_last.get(last_segment(target)); // 2. Suffix match let colon = format!("::{target}"); let dot = format!(".{target}"); if let Some(idx) = pick(candidates, from_file, |q| { q.ends_with(&colon) || q.ends_with(&dot) }) { return Some(idx); } // 3. Module path: match progressively shorter suffixes of the path, // without Rust's relative prefixes. if target.contains("::") { let stripped = target .strip_prefix("crate::") .or_else(|| target.strip_prefix("super::")) .or_else(|| target.strip_prefix("self::")) .unwrap_or(target); let segments: Vec<&str> = stripped.split("::").collect(); for start in 0..segments.len() { let pattern = format!("::{}", segments[start..].join("::")); if let Some(idx) = pick(candidates, from_file, |q| q.ends_with(&pattern)) { return Some(idx); } } } // 4. Self-method if let Some(method) = target.strip_prefix("self.") { let pattern = format!("::{method}"); if let Some(idx) = pick(candidates, from_file, |q| q.ends_with(&pattern)) { return Some(idx); } } // 5. File path let path = target.trim_start_matches("./"); let file_name = path.rsplit('/').next().unwrap_or(path); let in_dir = format!("/{path}"); pick(self.files_by_name.get(file_name), from_file, |q| { q == path || q.ends_with(&in_dir) }) } } /// The first candidate that `matches`, preferring one in `from_file`. fn pick( candidates: Option<&Vec>>, from_file: &str, matches: impl Fn(&str) -> bool, ) -> Option { let mut first = None; for candidate in candidates?.iter().filter(|c| matches(c.qualified)) { if candidate.file_path == from_file { return Some(candidate.idx); } first.get_or_insert(candidate.idx); } first } /// The main graph engine that builds and manages code knowledge graphs pub struct GraphEngine { parser_registry: ParserRegistry, max_nodes: u32, } /// In-memory representation of a built code graph pub struct CodeGraph { pub graph: DiGraph, pub node_map: HashMap, pub nodes: Vec, pub edges: Vec, } impl GraphEngine { pub fn new(max_nodes: u32) -> Self { Self { parser_registry: ParserRegistry::new(), max_nodes, } } /// Build a code graph from a repository directory pub fn build_graph( &self, repo_path: &Path, repo_id: &str, graph_build_id: &str, ) -> Result<(CodeGraph, GraphBuildRun), CoreError> { info!(repo_id, path = %repo_path.display(), "Starting graph build"); let parse_output = self.parser_registry.parse_directory( repo_path, repo_id, graph_build_id, self.max_nodes, )?; self.assemble(parse_output, repo_id) } /// Build a code graph from nodes and edges parsed elsewhere, e.g. by a /// parser outside this crate through [`crate::parsers::FileGraph`]: link /// the edges, detect communities and count what was built. /// /// # Arguments /// /// * `parse_output` - every file's nodes and edges, kept within the /// engine's node limit by the caller /// * `repo_id` - the repository the build run belongs to /// /// # Errors /// /// Returns `CoreError::Graph` when the graph can't be assembled. pub fn assemble( &self, parse_output: ParseOutput, repo_id: &str, ) -> Result<(CodeGraph, GraphBuildRun), CoreError> { let mut build_run = GraphBuildRun::new(repo_id.to_string()); let mut code_graph = self.build_petgraph(parse_output)?; let community_count = apply_communities(&mut code_graph); // Collect language stats let mut languages: Vec = code_graph .nodes .iter() .map(|n| n.language.clone()) .collect::>() .into_iter() .collect(); languages.sort(); build_run.node_count = code_graph.nodes.len() as u32; build_run.edge_count = code_graph.edges.len() as u32; build_run.community_count = community_count; build_run.languages_parsed = languages; build_run.status = GraphBuildStatus::Completed; build_run.completed_at = Some(Utc::now()); info!( nodes = build_run.node_count, edges = build_run.edge_count, communities = build_run.community_count, "Graph build complete" ); Ok((code_graph, build_run)) } /// Build petgraph from parsed output, resolving edges to node indices. /// /// After resolving the explicit edges from parsers, we synthesise /// `Contains` edges so that every node is reachable from its parent /// file or module. This eliminates disconnected "islands" that /// otherwise appear when files share no direct call/import edges. fn build_petgraph(&self, parse_output: ParseOutput) -> Result { let mut graph = DiGraph::new(); let mut node_map: HashMap = HashMap::new(); let mut nodes = parse_output.nodes; // Add all nodes to the graph for node in &mut nodes { let idx = graph.add_node(node.qualified_name.clone()); node.graph_index = Some(idx.index() as u32); node_map.insert(node.qualified_name.clone(), idx); } // Resolve and add explicit edges from parsers let index = NameIndex::new(&nodes, &node_map); let mut resolved_edges = Vec::new(); for mut edge in parse_output.edges { let source_idx = node_map.get(&edge.source); let resolved = index.resolve(&edge.target, &edge.file_path); if let (Some(&src), Some(tgt)) = (source_idx, resolved) { // A node's weight is its qualified name. edge.target = graph[tgt].clone(); graph.add_edge(src, tgt, edge.kind.clone()); resolved_edges.push(edge); } } // Synthesise Contains edges: connect each node to its closest // parent in the qualified-name hierarchy. // // For "src/main.rs::config::load", the parent chain is: // "src/main.rs::config" → "src/main.rs" // // We walk up the qualified name (splitting on "::") and link to // the first ancestor that exists in the node map. let repo_id = nodes.first().map(|n| n.repo_id.as_str()).unwrap_or(""); let build_id = nodes .first() .map(|n| n.graph_build_id.as_str()) .unwrap_or(""); let qualified_names: Vec = nodes.iter().map(|n| n.qualified_name.clone()).collect(); let file_paths: HashMap = nodes .iter() .map(|n| (n.qualified_name.clone(), n.file_path.clone())) .collect(); for qname in &qualified_names { if let Some(parent_qname) = find_parent_qname(qname, &node_map) { let child_idx = node_map[qname]; let parent_idx = node_map[&parent_qname]; // Avoid duplicate edges if !graph.contains_edge(parent_idx, child_idx) { graph.add_edge(parent_idx, child_idx, CodeEdgeKind::Contains); resolved_edges.push(CodeEdge { id: None, repo_id: repo_id.to_string(), graph_build_id: build_id.to_string(), source: parent_qname, target: qname.clone(), kind: CodeEdgeKind::Contains, file_path: file_paths.get(qname).cloned().unwrap_or_default(), line_number: None, }); } } } Ok(CodeGraph { graph, node_map, nodes, edges: resolved_edges, }) } /// Get the impact analyzer for a built graph pub fn impact_analyzer(code_graph: &CodeGraph) -> ImpactAnalyzer<'_> { ImpactAnalyzer::new(code_graph) } } #[cfg(test)] mod tests { use super::*; use compliance_core::models::graph::{CodeEdgeKind, CodeNode, CodeNodeKind}; fn make_node(qualified_name: &str) -> CodeNode { CodeNode { id: None, repo_id: "test".to_string(), graph_build_id: "build1".to_string(), qualified_name: qualified_name.to_string(), name: qualified_name .split("::") .last() .unwrap_or(qualified_name) .to_string(), kind: CodeNodeKind::Function, file_path: "src/main.rs".to_string(), start_line: 1, end_line: 10, language: "rust".to_string(), community_id: None, is_entry_point: false, graph_index: None, } } fn build_test_node_map(names: &[&str]) -> HashMap { let mut graph: DiGraph = DiGraph::new(); let mut map = HashMap::new(); for name in names { let idx = graph.add_node(name.to_string()); map.insert(name.to_string(), idx); } map } /// Resolve `target` from `src/main.rs` against nodes named `names`, /// returning the qualified name it resolved to. fn resolve(names: &[&str], target: &str) -> Option { resolve_from(names, target, "src/main.rs") } fn resolve_from(names: &[&str], target: &str, from_file: &str) -> Option { let nodes: Vec = names.iter().map(|n| make_node(n)).collect(); let node_map = build_test_node_map(names); NameIndex::new(&nodes, &node_map) .resolve(target, from_file) .map(|idx| names[idx.index()].to_string()) } #[test] fn test_resolve_edge_target_direct_match() { let result = resolve( &["src/main.rs::foo", "src/main.rs::bar"], "src/main.rs::foo", ); assert_eq!(result.as_deref(), Some("src/main.rs::foo")); } #[test] fn test_resolve_edge_target_short_name_match() { let result = resolve(&["src/main.rs::foo", "src/main.rs::bar"], "foo"); assert_eq!(result.as_deref(), Some("src/main.rs::foo")); } #[test] fn test_resolve_edge_target_method_match() { let result = resolve(&["src/main.rs::MyStruct::do_thing"], "do_thing"); assert!(result.is_some()); } #[test] fn test_resolve_edge_target_self_method() { let result = resolve(&["src/main.rs::MyStruct::process"], "self.process"); assert!(result.is_some()); } #[test] fn test_resolve_edge_target_no_match() { let result = resolve(&["src/main.rs::foo"], "nonexistent"); assert!(result.is_none()); } #[test] fn test_resolve_edge_target_empty_map() { let result = resolve(&[], "anything"); assert!(result.is_none()); } #[test] fn test_resolve_edge_target_dot_notation() { let result = resolve(&["src/app.js.handler"], "handler"); assert!(result.is_some()); } #[test] fn test_build_petgraph_empty() { let engine = GraphEngine::new(1000); let output = ParseOutput::default(); let code_graph = engine.build_petgraph(output).unwrap(); assert_eq!(code_graph.nodes.len(), 0); assert_eq!(code_graph.edges.len(), 0); assert_eq!(code_graph.graph.node_count(), 0); } #[test] fn test_build_petgraph_nodes_get_graph_index() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); output.nodes.push(make_node("src/main.rs::foo")); output.nodes.push(make_node("src/main.rs::bar")); let code_graph = engine.build_petgraph(output).unwrap(); assert_eq!(code_graph.nodes.len(), 2); assert_eq!(code_graph.graph.node_count(), 2); // All nodes should have a graph_index assigned for node in &code_graph.nodes { assert!(node.graph_index.is_some()); } } #[test] fn test_build_petgraph_resolves_edges() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); output.nodes.push(make_node("src/main.rs::foo")); output.nodes.push(make_node("src/main.rs::bar")); output.edges.push(CodeEdge { id: None, repo_id: "test".to_string(), graph_build_id: "build1".to_string(), source: "src/main.rs::foo".to_string(), target: "bar".to_string(), // short name, should resolve kind: CodeEdgeKind::Calls, file_path: "src/main.rs".to_string(), line_number: Some(5), }); let code_graph = engine.build_petgraph(output).unwrap(); assert_eq!(code_graph.edges.len(), 1); assert_eq!(code_graph.graph.edge_count(), 1); // The resolved edge target should be the full qualified name assert_eq!(code_graph.edges[0].target, "src/main.rs::bar"); } #[test] fn test_build_petgraph_skips_unresolved_edges() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); output.nodes.push(make_node("src/main.rs::foo")); output.edges.push(CodeEdge { id: None, repo_id: "test".to_string(), graph_build_id: "build1".to_string(), source: "src/main.rs::foo".to_string(), target: "external_crate::something".to_string(), kind: CodeEdgeKind::Calls, file_path: "src/main.rs".to_string(), line_number: Some(5), }); let code_graph = engine.build_petgraph(output).unwrap(); assert_eq!(code_graph.edges.len(), 0); assert_eq!(code_graph.graph.edge_count(), 0); } #[test] fn test_code_graph_node_map_consistency() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); output.nodes.push(make_node("a::b")); output.nodes.push(make_node("a::c")); output.nodes.push(make_node("a::d")); let code_graph = engine.build_petgraph(output).unwrap(); assert_eq!(code_graph.node_map.len(), 3); assert!(code_graph.node_map.contains_key("a::b")); assert!(code_graph.node_map.contains_key("a::c")); assert!(code_graph.node_map.contains_key("a::d")); } #[test] fn test_contains_edges_synthesised() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); // File → Module → Function hierarchy output.nodes.push(make_node("src/main.rs")); output.nodes.push(make_node("src/main.rs::config")); output.nodes.push(make_node("src/main.rs::config::load")); let code_graph = engine.build_petgraph(output).unwrap(); // Should have 2 Contains edges: // src/main.rs → src/main.rs::config // src/main.rs::config → src/main.rs::config::load let contains_edges: Vec<_> = code_graph .edges .iter() .filter(|e| matches!(e.kind, CodeEdgeKind::Contains)) .collect(); assert_eq!(contains_edges.len(), 2, "expected 2 Contains edges"); let sources: Vec<&str> = contains_edges.iter().map(|e| e.source.as_str()).collect(); assert!(sources.contains(&"src/main.rs")); assert!(sources.contains(&"src/main.rs::config")); } #[test] fn test_contains_edges_no_duplicates_with_existing_edges() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); output.nodes.push(make_node("src/main.rs")); output.nodes.push(make_node("src/main.rs::foo")); // Explicit Calls edge (foo calls itself? just for testing) output.edges.push(CodeEdge { id: None, repo_id: "test".to_string(), graph_build_id: "build1".to_string(), source: "src/main.rs::foo".to_string(), target: "src/main.rs::foo".to_string(), kind: CodeEdgeKind::Calls, file_path: "src/main.rs".to_string(), line_number: Some(1), }); let code_graph = engine.build_petgraph(output).unwrap(); // 1 Calls + 1 Contains = 2 edges total assert_eq!(code_graph.edges.len(), 2); } #[test] fn test_cross_file_resolution_with_module_path() { let result = resolve( &["src/config.rs::load_config", "src/main.rs::main"], "crate::config::load_config", ); assert!(result.is_some(), "cross-file crate:: path should resolve"); } fn node_in(qualified_name: &str, file_path: &str, kind: CodeNodeKind) -> CodeNode { CodeNode { file_path: file_path.to_string(), kind, ..make_node(qualified_name) } } fn edge_in(source: &str, target: &str, file_path: &str, kind: CodeEdgeKind) -> CodeEdge { CodeEdge { id: None, repo_id: "test".to_string(), graph_build_id: "build1".to_string(), source: source.to_string(), target: target.to_string(), kind, file_path: file_path.to_string(), line_number: Some(1), } } #[test] fn same_named_functions_resolve_within_the_calling_file() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); for (name, file) in [ ("b.c::helper", "b.c"), ("a.c::helper", "a.c"), ("a.c::main", "a.c"), ("b.c::run", "b.c"), ] { output .nodes .push(node_in(name, file, CodeNodeKind::Function)); } output .edges .push(edge_in("a.c::main", "helper", "a.c", CodeEdgeKind::Calls)); output .edges .push(edge_in("b.c::run", "helper", "b.c", CodeEdgeKind::Calls)); let code_graph = engine.build_petgraph(output).unwrap(); let targets: Vec<(&str, &str)> = code_graph .edges .iter() .filter(|e| matches!(e.kind, CodeEdgeKind::Calls)) .map(|e| (e.source.as_str(), e.target.as_str())) .collect(); assert_eq!( targets, [("a.c::main", "a.c::helper"), ("b.c::run", "b.c::helper")] ); } #[test] fn ambiguous_names_resolve_the_same_way_every_time() { let names = ["src/z.rs::helper", "src/b.rs::helper", "src/m.rs::helper"]; for _ in 0..20 { assert_eq!( resolve_from(&names, "helper", "src/other.rs").as_deref(), Some("src/b.rs::helper") ); } } #[test] fn includes_resolve_to_the_header_file() { let engine = GraphEngine::new(1000); let mut output = ParseOutput::default(); output .nodes .push(node_in("src/main.c", "src/main.c", CodeNodeKind::File)); output.nodes.push(node_in( "src/lib/uart.h", "src/lib/uart.h", CodeNodeKind::File, )); for target in [ "uart.h", "lib/uart.h", "./lib/uart.h", "stdio.h", "b/uart.h", ] { output.edges.push(edge_in( "src/main.c", target, "src/main.c", CodeEdgeKind::Imports, )); } let code_graph = engine.build_petgraph(output).unwrap(); let imports: Vec<&str> = code_graph .edges .iter() .filter(|e| matches!(e.kind, CodeEdgeKind::Imports)) .map(|e| e.target.as_str()) .collect(); assert_eq!( imports, ["src/lib/uart.h", "src/lib/uart.h", "src/lib/uart.h"] ); } #[test] fn last_segment_splits_paths_then_members() { assert_eq!(last_segment("src/a.py::Cls.run"), "run"); assert_eq!(last_segment("self.run"), "run"); assert_eq!(last_segment("crate::config::load"), "load"); assert_eq!(last_segment("main"), "main"); } #[test] fn test_find_parent_qname() { let node_map = build_test_node_map(&[ "src/main.rs", "src/main.rs::config", "src/main.rs::config::load", ]); assert_eq!( find_parent_qname("src/main.rs::config::load", &node_map), Some("src/main.rs::config".to_string()) ); assert_eq!( find_parent_qname("src/main.rs::config", &node_map), Some("src/main.rs".to_string()) ); assert_eq!(find_parent_qname("src/main.rs", &node_map), None); } }