diff --git a/.gitea/workflows/ci.yml b/.gitea/workflows/ci.yml index 72a7aed..1e5a4dc 100644 --- a/.gitea/workflows/ci.yml +++ b/.gitea/workflows/ci.yml @@ -138,6 +138,8 @@ jobs: run: cargo clippy -p werkbank-exec --all-targets -- -D warnings - name: Clippy (control-map) run: cargo clippy -p control-map --all-targets -- -D warnings + - name: Clippy (graph) + run: cargo clippy -p compliance-graph --all-targets -- -D warnings # Security audit - name: Security Audit @@ -146,8 +148,8 @@ jobs: RUSTC_WRAPPER: "" # Tests (reuses compilation artifacts from clippy) - - name: Tests (core + agent + werkbank-exec + control-map) - run: cargo test -p compliance-core -p compliance-agent -p werkbank-exec -p control-map --lib + - name: Tests (core + agent + graph + werkbank-exec + control-map) + run: cargo test -p compliance-core -p compliance-agent -p compliance-graph -p werkbank-exec -p control-map --lib # compliance-core's integration tests need no services. - name: Tests (core integration) run: cargo test -p compliance-core --tests diff --git a/Cargo.lock b/Cargo.lock index becfc85..7cd0d2a 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -757,6 +757,8 @@ dependencies = [ "tokio", "tracing", "tree-sitter", + "tree-sitter-c", + "tree-sitter-c-sharp", "tree-sitter-javascript", "tree-sitter-python", "tree-sitter-rust", @@ -6502,6 +6504,26 @@ dependencies = [ "tree-sitter-language", ] +[[package]] +name = "tree-sitter-c" +version = "0.23.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "afd2b1bf1585dc2ef6d69e87d01db8adb059006649dd5f96f31aa789ee6e9c71" +dependencies = [ + "cc", + "tree-sitter-language", +] + +[[package]] +name = "tree-sitter-c-sharp" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67f06accca7b45351758663b8215089e643d53bd9a660ce0349314263737fcb0" +dependencies = [ + "cc", + "tree-sitter-language", +] + [[package]] name = "tree-sitter-javascript" version = "0.23.1" diff --git a/compliance-agent/src/pipeline/graph_build.rs b/compliance-agent/src/pipeline/graph_build.rs index 2cbd99c..53d9e17 100644 --- a/compliance-agent/src/pipeline/graph_build.rs +++ b/compliance-agent/src/pipeline/graph_build.rs @@ -14,13 +14,10 @@ impl PipelineOrchestrator { let graph_build_id = uuid::Uuid::new_v4().to_string(); let engine = compliance_graph::GraphEngine::new(50_000); - let (mut code_graph, build_run) = - engine - .build_graph(repo_path, repo_id, &graph_build_id) - .map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?; - - // Apply community detection - compliance_graph::graph::community::apply_communities(&mut code_graph); + // The build assigns communities too. + let (code_graph, build_run) = engine + .build_graph(repo_path, repo_id, &graph_build_id) + .map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?; // Store graph in MongoDB let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner()); diff --git a/compliance-graph/Cargo.toml b/compliance-graph/Cargo.toml index ccf80d4..794c2f8 100644 --- a/compliance-graph/Cargo.toml +++ b/compliance-graph/Cargo.toml @@ -20,6 +20,8 @@ tree-sitter-rust = "0.23" tree-sitter-python = "0.23" tree-sitter-javascript = "0.23" tree-sitter-typescript = "0.23" +tree-sitter-c = "0.23" +tree-sitter-c-sharp = "=0.23.1" # Graph algorithms petgraph = "0.7" diff --git a/compliance-graph/src/graph/community.rs b/compliance-graph/src/graph/community.rs index f7225bd..44cb355 100644 --- a/compliance-graph/src/graph/community.rs +++ b/compliance-graph/src/graph/community.rs @@ -1,257 +1,143 @@ -use std::collections::HashMap; - -use petgraph::graph::NodeIndex; use petgraph::visit::EdgeRef; +use petgraph::Direction; use tracing::info; use super::engine::CodeGraph; +/// Louvain's local-move phase over the graph, read as undirected: each node +/// starts in its own community and moves to the neighbouring community with +/// the best modularity gain until no move helps (at most 50 passes). +/// +/// The community degree totals are kept up to date on every move instead of +/// being summed again for every node, and a node's edges per neighbouring +/// community are counted in a scratch array, so one pass costs +/// O(nodes + edges). Communities are numbered 0.. in node order, so the +/// same graph always gets the same numbers. +/// +/// # Returns +/// +/// The community of every node, indexed by node index. +fn louvain(code_graph: &CodeGraph) -> Vec { + let graph = &code_graph.graph; + let node_count = graph.node_count(); + let mut community: Vec = (0..node_count as u32).collect(); + if graph.edge_count() == 0 { + return community; + } + let m2 = 2.0 * graph.edge_count() as f64; + + // Neighbours in both directions, once, as plain indices. + let neighbours: Vec> = graph + .node_indices() + .map(|idx| { + graph + .edges_directed(idx, Direction::Outgoing) + .map(|e| e.target().index()) + .chain( + graph + .edges_directed(idx, Direction::Incoming) + .map(|e| e.source().index()), + ) + .collect() + }) + .collect(); + let degree: Vec = neighbours.iter().map(|n| n.len() as f64).collect(); + let mut totals = degree.clone(); + + // Edges from the current node into each community; `touched` lists the + // communities set, so only those are reset. + let mut edges_to = vec![0.0_f64; node_count]; + let mut touched: Vec = Vec::new(); + + for _ in 0..50 { + let mut improved = false; + for node in 0..node_count { + let current = community[node]; + let node_degree = degree[node]; + for &neighbour in &neighbours[node] { + let c = community[neighbour]; + if edges_to[c as usize] == 0.0 { + touched.push(c); + } + edges_to[c as usize] += 1.0; + } + + let remove_cost = edges_to[current as usize] + - (totals[current as usize] - node_degree) * node_degree / m2; + let mut best = current; + let mut best_gain = 0.0; + for &candidate in &touched { + if candidate == current { + continue; + } + let gain = edges_to[candidate as usize] + - totals[candidate as usize] * node_degree / m2 + - remove_cost; + if gain > best_gain { + best_gain = gain; + best = candidate; + } + } + for &c in &touched { + edges_to[c as usize] = 0.0; + } + touched.clear(); + + if best != current { + totals[current as usize] -= node_degree; + totals[best as usize] += node_degree; + community[node] = best; + improved = true; + } + } + if !improved { + break; + } + } + + // Renumber 0.. in order of first appearance. + let mut renumbered = vec![u32::MAX; node_count]; + let mut next = 0; + for c in &mut community { + let slot = &mut renumbered[*c as usize]; + if *slot == u32::MAX { + *slot = next; + next += 1; + } + *c = *slot; + } + community +} + +/// The number of communities in a node assignment numbered 0... +fn count(communities: &[u32]) -> u32 { + communities.iter().max().map_or(0, |max| max + 1) +} + /// Run Louvain community detection on the code graph. -/// Returns the number of communities detected. -/// Mutates node community_id in place. +/// +/// # Returns +/// +/// The number of communities detected. pub fn detect_communities(code_graph: &CodeGraph) -> u32 { - let graph = &code_graph.graph; - let node_count = graph.node_count(); - - if node_count == 0 { - return 0; - } - - // Initialize: each node in its own community - let mut community: HashMap = HashMap::new(); - for idx in graph.node_indices() { - community.insert(idx, idx.index() as u32); - } - - // Compute total edge weight (all edges weight 1.0) - let total_edges = graph.edge_count() as f64; - if total_edges == 0.0 { - // All nodes are isolated, each is its own community - return node_count as u32; - } - - let m2 = 2.0 * total_edges; - - // Pre-compute node degrees - let mut degree: HashMap = HashMap::new(); - for idx in graph.node_indices() { - let d = graph.edges(idx).count() as f64; - degree.insert(idx, d); - } - - // Louvain phase 1: local moves - let mut improved = true; - let mut iterations = 0; - let max_iterations = 50; - - while improved && iterations < max_iterations { - improved = false; - iterations += 1; - - for node in graph.node_indices() { - let current_comm = community[&node]; - let node_deg = degree[&node]; - - // Compute edges to each neighboring community - let mut comm_edges: HashMap = HashMap::new(); - for edge in graph.edges(node) { - let neighbor = edge.target(); - let neighbor_comm = community[&neighbor]; - *comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0; - } - // Also check incoming edges (undirected treatment) - for edge in graph.edges_directed(node, petgraph::Direction::Incoming) { - let neighbor = edge.source(); - let neighbor_comm = community[&neighbor]; - *comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0; - } - - // Compute community totals (sum of degrees in each community) - let mut comm_totals: HashMap = HashMap::new(); - for (n, &c) in &community { - *comm_totals.entry(c).or_insert(0.0) += degree[n]; - } - - // Find best community - let current_total = comm_totals.get(¤t_comm).copied().unwrap_or(0.0); - let edges_to_current = comm_edges.get(¤t_comm).copied().unwrap_or(0.0); - - // Modularity gain from removing node from current community - let remove_cost = edges_to_current - (current_total - node_deg) * node_deg / m2; - - let mut best_comm = current_comm; - let mut best_gain = 0.0; - - for (&candidate_comm, &edges_to_candidate) in &comm_edges { - if candidate_comm == current_comm { - continue; - } - let candidate_total = comm_totals.get(&candidate_comm).copied().unwrap_or(0.0); - - // Modularity gain from adding node to candidate community - let add_gain = edges_to_candidate - candidate_total * node_deg / m2; - let gain = add_gain - remove_cost; - - if gain > best_gain { - best_gain = gain; - best_comm = candidate_comm; - } - } - - if best_comm != current_comm { - community.insert(node, best_comm); - improved = true; - } - } - } - - // Renumber communities to be contiguous - let mut comm_remap: HashMap = HashMap::new(); - let mut next_id: u32 = 0; - for &c in community.values() { - if let std::collections::hash_map::Entry::Vacant(e) = comm_remap.entry(c) { - e.insert(next_id); - next_id += 1; - } - } - - // Apply to community map - for c in community.values_mut() { - if let Some(&new_id) = comm_remap.get(c) { - *c = new_id; - } - } - - let num_communities = next_id; - info!( - communities = num_communities, - iterations, "Community detection complete" - ); - - // NOTE: community IDs are stored in the HashMap but need to be applied - // back to the CodeGraph nodes by the caller (engine) if needed for persistence. - // For now we return the count; the full assignment is available via the map. - - num_communities + count(&louvain(code_graph)) } -/// Apply community assignments back to code nodes +/// Detect communities and write each node's community into `community_id`. +/// +/// # Returns +/// +/// The number of communities detected. pub fn apply_communities(code_graph: &mut CodeGraph) -> u32 { - detect_communities_with_assignment(code_graph) -} - -/// Detect communities and write assignments into the nodes -fn detect_communities_with_assignment(code_graph: &mut CodeGraph) -> u32 { - let graph = &code_graph.graph; - let node_count = graph.node_count(); - - if node_count == 0 { - return 0; - } - - let mut community: HashMap = HashMap::new(); - for idx in graph.node_indices() { - community.insert(idx, idx.index() as u32); - } - - let total_edges = graph.edge_count() as f64; - if total_edges == 0.0 { - for node in &mut code_graph.nodes { - if let Some(gi) = node.graph_index { - node.community_id = Some(gi); - } - } - return node_count as u32; - } - - let m2 = 2.0 * total_edges; - - let mut degree: HashMap = HashMap::new(); - for idx in graph.node_indices() { - let d = (graph.edges(idx).count() - + graph - .edges_directed(idx, petgraph::Direction::Incoming) - .count()) as f64; - degree.insert(idx, d); - } - - let mut improved = true; - let mut iterations = 0; - let max_iterations = 50; - - while improved && iterations < max_iterations { - improved = false; - iterations += 1; - - for node in graph.node_indices() { - let current_comm = community[&node]; - let node_deg = degree[&node]; - - let mut comm_edges: HashMap = HashMap::new(); - for edge in graph.edges(node) { - let neighbor_comm = community[&edge.target()]; - *comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0; - } - for edge in graph.edges_directed(node, petgraph::Direction::Incoming) { - let neighbor_comm = community[&edge.source()]; - *comm_edges.entry(neighbor_comm).or_insert(0.0) += 1.0; - } - - let mut comm_totals: HashMap = HashMap::new(); - for (n, &c) in &community { - *comm_totals.entry(c).or_insert(0.0) += degree[n]; - } - - let current_total = comm_totals.get(¤t_comm).copied().unwrap_or(0.0); - let edges_to_current = comm_edges.get(¤t_comm).copied().unwrap_or(0.0); - let remove_cost = edges_to_current - (current_total - node_deg) * node_deg / m2; - - let mut best_comm = current_comm; - let mut best_gain = 0.0; - - for (&candidate_comm, &edges_to_candidate) in &comm_edges { - if candidate_comm == current_comm { - continue; - } - let candidate_total = comm_totals.get(&candidate_comm).copied().unwrap_or(0.0); - let add_gain = edges_to_candidate - candidate_total * node_deg / m2; - let gain = add_gain - remove_cost; - - if gain > best_gain { - best_gain = gain; - best_comm = candidate_comm; - } - } - - if best_comm != current_comm { - community.insert(node, best_comm); - improved = true; - } - } - } - - // Renumber - let mut comm_remap: HashMap = HashMap::new(); - let mut next_id: u32 = 0; - for &c in community.values() { - if let std::collections::hash_map::Entry::Vacant(e) = comm_remap.entry(c) { - e.insert(next_id); - next_id += 1; - } - } - - // Apply to nodes + let communities = louvain(code_graph); for node in &mut code_graph.nodes { - if let Some(gi) = node.graph_index { - let idx = NodeIndex::new(gi as usize); - if let Some(&comm) = community.get(&idx) { - let remapped = comm_remap.get(&comm).copied().unwrap_or(comm); - node.community_id = Some(remapped); - } + if let Some(&community) = node.graph_index.and_then(|gi| communities.get(gi as usize)) { + node.community_id = Some(community); } } - - next_id + let communities = count(&communities); + info!(communities, "Community detection complete"); + communities } #[cfg(test)] @@ -259,6 +145,7 @@ mod tests { use super::*; use compliance_core::models::graph::{CodeEdgeKind, CodeNode, CodeNodeKind}; use petgraph::graph::DiGraph; + use std::collections::HashMap; fn make_node(qualified_name: &str, graph_index: u32) -> CodeNode { CodeNode { diff --git a/compliance-graph/src/graph/engine.rs b/compliance-graph/src/graph/engine.rs index c44c2c8..e21ca60 100644 --- a/compliance-graph/src/graph/engine.rs +++ b/compliance-graph/src/graph/engine.rs @@ -4,7 +4,7 @@ use std::path::Path; use chrono::Utc; use compliance_core::error::CoreError; use compliance_core::models::graph::{ - CodeEdge, CodeEdgeKind, CodeNode, GraphBuildRun, GraphBuildStatus, + CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind, GraphBuildRun, GraphBuildStatus, }; use compliance_core::traits::graph_builder::ParseOutput; use petgraph::graph::{DiGraph, NodeIndex}; @@ -12,7 +12,7 @@ use tracing::info; use crate::parsers::registry::ParserRegistry; -use super::community::detect_communities; +use super::community::apply_communities; use super::impact::ImpactAnalyzer; /// Walk up the qualified-name hierarchy to find the closest ancestor @@ -39,6 +39,141 @@ fn find_parent_qname(qname: &str, node_map: &HashMap) -> Opti } } +/// 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, @@ -81,10 +216,10 @@ impl GraphEngine { )?; // Phase 2: Build petgraph - let code_graph = self.build_petgraph(parse_output)?; + let mut code_graph = self.build_petgraph(parse_output)?; // Phase 3: Run community detection - let community_count = detect_communities(&code_graph); + let community_count = apply_communities(&mut code_graph); // Collect language stats let mut languages: Vec = code_graph @@ -132,19 +267,15 @@ impl GraphEngine { } // 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 = self.resolve_edge_target(&edge.target, &node_map); + let resolved = index.resolve(&edge.target, &edge.file_path); if let (Some(&src), Some(tgt)) = (source_idx, resolved) { - let resolved_name = node_map - .iter() - .find(|(_, &idx)| idx == tgt) - .map(|(name, _)| name.clone()); - if let Some(name) = resolved_name { - edge.target = name; - } + // 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); } @@ -200,70 +331,6 @@ impl GraphEngine { }) } - /// Try to resolve an edge target to a known node. - /// - /// Resolution strategies (in order): - /// 1. Direct qualified-name match - /// 2. Suffix match: "foo" matches "src/main.rs::mod::foo" - /// 3. Module-path match: "config::load" matches "src/config.rs::load" - /// 4. Self-method: "self.method" matches "::method" - fn resolve_edge_target( - &self, - target: &str, - node_map: &HashMap, - ) -> Option { - // 1. Direct match - if let Some(idx) = node_map.get(target) { - return Some(*idx); - } - - // 2. Suffix match: "foo" → "path/file.rs::foo" - let suffix_pattern = format!("::{target}"); - let dot_pattern = format!(".{target}"); - for (qualified, idx) in node_map { - if qualified.ends_with(&suffix_pattern) || qualified.ends_with(&dot_pattern) { - return Some(*idx); - } - } - - // 3. Module-path match: "config::load" → try matching the last N - // segments of the target against node qualified names. - // This handles cross-file calls like `crate::config::load` or - // `super::handlers::process` where the prefix differs. - if target.contains("::") { - // Strip common Rust path prefixes - 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(); - // Try matching progressively shorter suffixes - for start in 0..segments.len() { - let suffix = segments[start..].join("::"); - let pattern = format!("::{suffix}"); - for (qualified, idx) in node_map { - if qualified.ends_with(&pattern) { - return Some(*idx); - } - } - } - } - - // 4. Self-method: "self.method" → "::method" - if let Some(method_name) = target.strip_prefix("self.") { - let pattern = format!("::{method_name}"); - for (qualified, idx) in node_map { - if qualified.ends_with(&pattern) { - return Some(*idx); - } - } - } - - None - } - /// Get the impact analyzer for a built graph pub fn impact_analyzer(code_graph: &CodeGraph) -> ImpactAnalyzer<'_> { ImpactAnalyzer::new(code_graph) @@ -307,61 +374,62 @@ mod tests { 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 engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/main.rs::foo", "src/main.rs::bar"]); - let result = engine.resolve_edge_target("src/main.rs::foo", &node_map); - assert!(result.is_some()); - assert_eq!(result.unwrap(), node_map["src/main.rs::foo"]); + 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 engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/main.rs::foo", "src/main.rs::bar"]); - let result = engine.resolve_edge_target("foo", &node_map); - assert!(result.is_some()); - assert_eq!(result.unwrap(), node_map["src/main.rs::foo"]); + 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 engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/main.rs::MyStruct::do_thing"]); - let result = engine.resolve_edge_target("do_thing", &node_map); + let result = resolve(&["src/main.rs::MyStruct::do_thing"], "do_thing"); assert!(result.is_some()); } #[test] fn test_resolve_edge_target_self_method() { - let engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/main.rs::MyStruct::process"]); - let result = engine.resolve_edge_target("self.process", &node_map); + let result = resolve(&["src/main.rs::MyStruct::process"], "self.process"); assert!(result.is_some()); } #[test] fn test_resolve_edge_target_no_match() { - let engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/main.rs::foo"]); - let result = engine.resolve_edge_target("nonexistent", &node_map); + let result = resolve(&["src/main.rs::foo"], "nonexistent"); assert!(result.is_none()); } #[test] fn test_resolve_edge_target_empty_map() { - let engine = GraphEngine::new(1000); - let node_map = HashMap::new(); - let result = engine.resolve_edge_target("anything", &node_map); + let result = resolve(&[], "anything"); assert!(result.is_none()); } #[test] fn test_resolve_edge_target_dot_notation() { - let engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/app.js.handler"]); - let result = engine.resolve_edge_target("handler", &node_map); + let result = resolve(&["src/app.js.handler"], "handler"); assert!(result.is_some()); } @@ -504,13 +572,127 @@ mod tests { #[test] fn test_cross_file_resolution_with_module_path() { - let engine = GraphEngine::new(1000); - let node_map = build_test_node_map(&["src/config.rs::load_config", "src/main.rs::main"]); - // "crate::config::load_config" should resolve to "src/config.rs::load_config" - let result = engine.resolve_edge_target("crate::config::load_config", &node_map); + 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(&[ diff --git a/compliance-graph/src/parsers/c.rs b/compliance-graph/src/parsers/c.rs new file mode 100644 index 0000000..0cd4bc0 --- /dev/null +++ b/compliance-graph/src/parsers/c.rs @@ -0,0 +1,383 @@ +//! C, as in embedded firmware: functions, structs, unions and enums, calls +//! and `#include`s. Interrupt handlers count as entry points, in the +//! spellings of the compilers our customers use: avr-gcc's `ISR(vector)`, +//! CodeVision's `interrupt [vector]`, SDCC's `__interrupt(n)`, IAR's +//! `__interrupt` and GCC's `__attribute__((interrupt))` / `((signal))`. + +use std::path::Path; + +use compliance_core::error::CoreError; +use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind}; +use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput}; +use tree_sitter::Node; + +use super::common::{parse, text, walk, FileGraph}; + +/// avr-gcc's interrupt macros, which tree-sitter reads as a function whose +/// return type is the macro and whose name is the vector: `ISR(TIMER1_vect)`. +const ISR_MACROS: [&str; 3] = ["ISR", "SIGNAL", "INTERRUPT"]; + +/// Parses C sources and headers. +#[derive(Debug, Default)] +pub struct CParser; + +impl CParser { + /// A C parser. + pub fn new() -> Self { + Self + } + + /// Visit the declarations of a translation unit, including those inside + /// `#if`/`#ifdef` blocks, without descending into function bodies. + fn walk_declarations(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) { + walk(root, |node| match node.kind() { + "function_definition" => { + Self::function(node, source, graph); + false + } + "type_definition" => { + Self::typedef(node, source, graph); + false + } + "struct_specifier" | "union_specifier" | "enum_specifier" => { + Self::record(node, None, source, graph); + false + } + _ => true, + }); + } + + fn function(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) { + let Some(declarator) = node.child_by_field_name("declarator") else { + return; + }; + let Some(name_node) = declarator_name(declarator) else { + return; + }; + let raw_name = text(name_node, source); + let return_type = node + .child_by_field_name("type") + .map(|t| text(t, source)) + .unwrap_or(""); + + // `ISR(TIMER1_vect)` is named after its vector. + let isr_macro = ISR_MACROS.contains(&return_type); + let name = if isr_macro { + format!("{return_type}({raw_name})") + } else { + raw_name.to_string() + }; + let is_entry = name == "main" || isr_macro || is_interrupt_handler(node, name_node, source); + + let qualified = graph.top_level(&name); + graph.node( + qualified.clone(), + &name, + CodeNodeKind::Function, + node, + is_entry, + ); + if let Some(body) = node.child_by_field_name("body") { + Self::calls(body, &qualified, source, graph); + } + } + + /// `typedef struct { … } name_t;` declares the struct under the typedef's + /// name when the struct itself has none. + fn typedef(node: Node<'_>, source: &str, graph: &mut FileGraph<'_>) { + let Some(ty) = node.child_by_field_name("type") else { + return; + }; + if !matches!( + ty.kind(), + "struct_specifier" | "union_specifier" | "enum_specifier" + ) { + return; + } + let alias = node + .child_by_field_name("declarator") + .filter(|d| d.kind() == "type_identifier") + .map(|d| text(d, source)); + Self::record(ty, alias, source, graph); + } + + /// A struct, union or enum with a body; a bare reference such as + /// `struct point p;` declares nothing. + fn record(node: Node<'_>, alias: Option<&str>, source: &str, graph: &mut FileGraph<'_>) { + if node.child_by_field_name("body").is_none() { + return; + } + let Some(name) = node + .child_by_field_name("name") + .map(|n| text(n, source)) + .or(alias) + else { + return; + }; + let kind = if node.kind() == "enum_specifier" { + CodeNodeKind::Enum + } else { + CodeNodeKind::Struct + }; + let qualified = graph.top_level(name); + graph.node(qualified, name, kind, node, false); + } + + /// Calls by name inside a function body. Calls through a function pointer + /// (`s->cb()`) are left out: their target can't be known from the source. + fn calls(body: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) { + walk(body, |node| { + if node.kind() == "call_expression" { + if let Some(callee) = node + .child_by_field_name("function") + .filter(|f| f.kind() == "identifier") + { + graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node); + } + } + true + }); + } + + fn includes(root: Node<'_>, source: &str, graph: &mut FileGraph<'_>) { + let file = graph.file_path().to_string(); + walk(root, |node| { + if node.kind() == "preproc_include" { + if let Some(path) = node.child_by_field_name("path") { + let target = text(path, source).trim_matches(['"', '<', '>']); + graph.edge(&file, target, CodeEdgeKind::Imports, node); + } + return false; + } + // Includes sit at file level or inside preprocessor blocks. + node.kind() == "translation_unit" || node.kind().starts_with("preproc_") + }); + } +} + +/// The identifier a declarator names, through pointers, parentheses and +/// attributes: `*make(void)` names `make`. +fn declarator_name(declarator: Node<'_>) -> Option> { + let mut current = declarator; + loop { + if current.kind() == "identifier" { + return Some(current); + } + current = current + .child_by_field_name("declarator") + .or_else(|| current.named_child(0))?; + } +} + +/// Header tokens that mark an interrupt handler: IAR's and CodeVision's +/// `interrupt`, SDCC's `__interrupt(n)`, GCC's `__attribute__((interrupt))` +/// and avr-gcc's `__attribute__((signal))`. +const INTERRUPT_TOKENS: [&str; 5] = [ + "interrupt", + "__interrupt", + "__interrupt__", + "signal", + "__signal__", +]; + +/// Whether the function header marks an interrupt handler. The header is +/// everything before the body except the name and the parameter list, so +/// neither `interrupt_flag_clear` nor a parameter named `signal` counts. +/// CodeVision's `interrupt [vector]` stands right before the function, and +/// tree-sitter reads it as a separate statement. +fn is_interrupt_handler(function: Node<'_>, name: Node<'_>, source: &str) -> bool { + let header_end = function + .child_by_field_name("body") + .map_or(function.end_byte(), |b| b.start_byte()); + let after_name = parameter_list(function) + .map_or(name.end_byte(), |p| p.end_byte()) + .min(header_end); + let header = [ + &source[function.start_byte()..name.start_byte()], + &source[after_name..header_end], + ]; + let marked = header.iter().any(|part| { + part.split(|c: char| !(c.is_ascii_alphanumeric() || c == '_')) + .any(|token| INTERRUPT_TOKENS.contains(&token)) + }); + marked + || function + .prev_named_sibling() + .filter(|prev| prev.kind() == "expression_statement") + .is_some_and(|prev| text(prev, source).trim_start().starts_with("interrupt")) +} + +/// The parameter list of a function definition, found through the same +/// declarator chain as its name. +fn parameter_list(function: Node<'_>) -> Option> { + let mut current = function.child_by_field_name("declarator")?; + loop { + if current.kind() == "function_declarator" { + return current.child_by_field_name("parameters"); + } + current = current + .child_by_field_name("declarator") + .or_else(|| current.named_child(0))?; + } +} + +impl LanguageParser for CParser { + fn language(&self) -> &str { + "c" + } + + fn extensions(&self) -> &[&str] { + &["c", "h"] + } + + fn parse_file( + &self, + file_path: &Path, + source: &str, + repo_id: &str, + graph_build_id: &str, + ) -> Result { + let tree = parse(tree_sitter_c::LANGUAGE.into(), source, "C")?; + let mut graph = FileGraph::new(file_path, source, repo_id, graph_build_id, "c"); + Self::walk_declarations(tree.root_node(), source, &mut graph); + Self::includes(tree.root_node(), source, &mut graph); + Ok(graph.finish()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::graph::CodeNode; + + const FIRMWARE: &str = r#" +#include "uart.h" +#include +static int helper(int a) { return a + 1; } +int *make(void) { return 0; } +struct point { int x; int y; }; +struct point origin; +typedef struct { int a; } cfg_t; +enum mode { A, B }; +#ifdef DEBUG +void trace(void) { helper(0); } +#endif +interrupt [TIM0_OVF] void timer0_ovf_isr(void) { helper(2); } +void ext_isr(void) __interrupt(1) { helper(3); } +__attribute__((__interrupt__)) static void avr32_isr(void) { helper(4); } +ISR(TIMER1_vect) { helper(5); } +void interrupt_flag_clear(void) { } +void on_event(int signal) { } +interrupt_state_t save_state(void) { return 0; } +int main(void) { uart_init(); helper(1); s->cb(2); return 0; } +"#; + + fn parsed() -> ParseOutput { + CParser::new() + .parse_file(Path::new("src/main.c"), FIRMWARE, "repo", "build") + .expect("C parses") + } + + fn node<'a>(out: &'a ParseOutput, name: &str) -> &'a CodeNode { + out.nodes + .iter() + .find(|n| n.name == name) + .unwrap_or_else(|| panic!("no node {name}")) + } + + #[test] + fn functions_records_and_the_file_become_nodes() { + let out = parsed(); + assert!(matches!(node(&out, "main.c").kind, CodeNodeKind::File)); + for function in ["helper", "make", "trace", "main"] { + assert!(matches!(node(&out, function).kind, CodeNodeKind::Function)); + } + assert!(matches!(node(&out, "point").kind, CodeNodeKind::Struct)); + assert!(matches!(node(&out, "cfg_t").kind, CodeNodeKind::Struct)); + assert!(matches!(node(&out, "mode").kind, CodeNodeKind::Enum)); + assert_eq!(node(&out, "helper").qualified_name, "src/main.c::helper"); + assert_eq!(node(&out, "helper").start_line, 4); + // `struct point origin;` only uses the struct. + assert_eq!(out.nodes.iter().filter(|n| n.name == "point").count(), 1); + } + + #[test] + fn main_and_every_interrupt_spelling_are_entry_points() { + let out = parsed(); + for entry in [ + "main", + "timer0_ovf_isr", + "ext_isr", + "avr32_isr", + "ISR(TIMER1_vect)", + ] { + assert!( + node(&out, entry).is_entry_point, + "{entry} is an entry point" + ); + } + for plain in [ + "helper", + "make", + "trace", + "interrupt_flag_clear", + "on_event", + "save_state", + ] { + assert!(!node(&out, plain).is_entry_point, "{plain} is not"); + } + } + + #[test] + fn calls_by_name_and_includes_become_edges() { + let out = parsed(); + let calls: Vec<(&str, &str)> = out + .edges + .iter() + .filter(|e| matches!(e.kind, CodeEdgeKind::Calls)) + .map(|e| (e.source.as_str(), e.target.as_str())) + .collect(); + assert!(calls.contains(&("src/main.c::main", "uart_init"))); + assert!(calls.contains(&("src/main.c::main", "helper"))); + assert!(calls.contains(&("src/main.c::ISR(TIMER1_vect)", "helper"))); + // A call through a function pointer has no target we can name. + assert!(!calls.iter().any(|(_, target)| target.contains("cb"))); + + let includes: Vec<&str> = out + .edges + .iter() + .filter(|e| matches!(e.kind, CodeEdgeKind::Imports)) + .map(|e| e.target.as_str()) + .collect(); + assert_eq!(includes, ["uart.h", "avr/io.h"]); + } + + #[test] + fn ifdef_alternatives_share_one_node() { + let source = "#ifdef FAST\nvoid init(void) { fast(); }\n#else\nvoid init(void) { slow(); }\n#endif\n"; + let out = CParser::new() + .parse_file(Path::new("i.c"), source, "r", "b") + .expect("C parses"); + assert_eq!(out.nodes.iter().filter(|n| n.name == "init").count(), 1); + let callees: Vec<&str> = out + .edges + .iter() + .filter(|e| matches!(e.kind, CodeEdgeKind::Calls)) + .map(|e| e.target.as_str()) + .collect(); + assert_eq!(callees, ["fast", "slow"]); + } + + #[test] + fn broken_code_still_yields_what_parses() { + let out = CParser::new() + .parse_file( + Path::new("bad.c"), + "void ok(void) {}\nint broken( {\n", + "r", + "b", + ) + .expect("a syntax error is not a failure"); + assert!(out.nodes.iter().any(|n| n.name == "ok")); + } +} diff --git a/compliance-graph/src/parsers/common.rs b/compliance-graph/src/parsers/common.rs new file mode 100644 index 0000000..61d3e43 --- /dev/null +++ b/compliance-graph/src/parsers/common.rs @@ -0,0 +1,189 @@ +//! Shared building blocks for the tree-sitter parsers: parsing a file with a +//! grammar, collecting its nodes and edges, and walking a subtree without +//! recursion. + +use std::collections::HashMap; +use std::path::Path; + +use compliance_core::error::CoreError; +use compliance_core::models::graph::{CodeEdge, CodeEdgeKind, CodeNode, CodeNodeKind}; +use compliance_core::traits::graph_builder::ParseOutput; +use tree_sitter::{Language, Node, Parser, Tree}; + +/// Parse `source` with `language`. +/// +/// # Errors +/// +/// Returns `CoreError::Graph` when the grammar can't be loaded (an ABI the +/// tree-sitter core doesn't support) or the parser gives up. +pub(crate) fn parse(language: Language, source: &str, name: &str) -> Result { + let mut parser = Parser::new(); + parser + .set_language(&language) + .map_err(|e| CoreError::Graph(format!("Failed to set {name} language: {e}")))?; + parser + .parse(source, None) + .ok_or_else(|| CoreError::Graph(format!("Failed to parse {name} file"))) +} + +/// The source text a syntax node covers. +pub(crate) fn text<'s>(node: Node<'_>, source: &'s str) -> &'s str { + &source[node.byte_range()] +} + +/// The 1-based line a syntax node starts on. +pub(crate) fn line(node: Node<'_>) -> u32 { + node.start_position().row as u32 + 1 +} + +/// Call `visit` on `root` and every node below it, depth first, with a +/// cursor instead of recursion, so deeply nested generated code can't +/// overflow the stack. `visit` returns whether to descend into that node. +pub(crate) fn walk(root: Node<'_>, mut visit: impl FnMut(Node<'_>) -> bool) { + let mut cursor = root.walk(); + loop { + if visit(cursor.node()) && cursor.goto_first_child() { + continue; + } + // No (wanted) children: move to the next sibling, climbing up until + // one exists or we are back at `root`. + loop { + if cursor.node() == root { + return; + } + if cursor.goto_next_sibling() { + break; + } + if !cursor.goto_parent() { + return; + } + } + } +} + +/// The nodes and edges of one file, with the identifiers every one of them +/// carries filled in once. +pub(crate) struct FileGraph<'a> { + repo_id: &'a str, + graph_build_id: &'a str, + file_path: String, + language: &'static str, + output: ParseOutput, + /// Qualified names already added: overloads (`Get(int)`, `Get(string)`) + /// and `#ifdef`/`#else` alternatives share one, and the graph keys nodes + /// by it. + seen: HashMap, +} + +impl<'a> FileGraph<'a> { + /// Start a file's graph with its `File` node. + pub(crate) fn new( + file_path: &Path, + source: &str, + repo_id: &'a str, + graph_build_id: &'a str, + language: &'static str, + ) -> Self { + let file_path_str = file_path.to_string_lossy().into_owned(); + let mut graph = Self { + repo_id, + graph_build_id, + file_path: file_path_str.clone(), + language, + output: ParseOutput::default(), + seen: HashMap::new(), + }; + let name = file_path + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + let end_line = source.lines().count() as u32; + graph.push_node(file_path_str, name, CodeNodeKind::File, 1, end_line, false); + graph + } + + /// The file's path, which is also its `File` node's qualified name. + pub(crate) fn file_path(&self) -> &str { + &self.file_path + } + + /// The qualified name of a top-level declaration named `name`. + pub(crate) fn top_level(&self, name: &str) -> String { + format!("{}::{name}", self.file_path) + } + + /// Add a declaration spanning `node`. A second declaration under the + /// same qualified name (an overload, an `#else` alternative) adds no + /// node; edges from its body still count, from the first one's node. + pub(crate) fn node( + &mut self, + qualified_name: String, + name: &str, + kind: CodeNodeKind, + node: Node<'_>, + is_entry_point: bool, + ) { + let end_line = node.end_position().row as u32 + 1; + self.push_node( + qualified_name, + name.to_string(), + kind, + line(node), + end_line, + is_entry_point, + ); + } + + fn push_node( + &mut self, + qualified_name: String, + name: String, + kind: CodeNodeKind, + start_line: u32, + end_line: u32, + is_entry_point: bool, + ) { + if let Some(&first) = self.seen.get(&qualified_name) { + // An overload that is an entry point makes the shared node one. + self.output.nodes[first].is_entry_point |= is_entry_point; + return; + } + self.seen + .insert(qualified_name.clone(), self.output.nodes.len()); + self.output.nodes.push(CodeNode { + id: None, + repo_id: self.repo_id.to_string(), + graph_build_id: self.graph_build_id.to_string(), + qualified_name, + name, + kind, + file_path: self.file_path.clone(), + start_line, + end_line, + language: self.language.to_string(), + community_id: None, + is_entry_point, + graph_index: None, + }); + } + + /// Add an edge from `source` to `target`, which the engine resolves + /// later (a bare name is fine). + pub(crate) fn edge(&mut self, source: &str, target: &str, kind: CodeEdgeKind, at: Node<'_>) { + self.output.edges.push(CodeEdge { + id: None, + repo_id: self.repo_id.to_string(), + graph_build_id: self.graph_build_id.to_string(), + source: source.to_string(), + target: target.to_string(), + kind, + file_path: self.file_path.clone(), + line_number: Some(line(at)), + }); + } + + /// The finished nodes and edges. + pub(crate) fn finish(self) -> ParseOutput { + self.output + } +} diff --git a/compliance-graph/src/parsers/csharp.rs b/compliance-graph/src/parsers/csharp.rs new file mode 100644 index 0000000..6066789 --- /dev/null +++ b/compliance-graph/src/parsers/csharp.rs @@ -0,0 +1,455 @@ +//! C#: classes, structs, interfaces, records and enums, their methods and +//! constructors, base types, and calls. Entry points are `Main` and what a +//! web framework calls from outside: ASP.NET controller actions, Razor page +//! handlers, Web Forms pages and controls, ASMX web methods and HTTP +//! handlers. +//! +//! `using` directives are left out: the graph has no namespace nodes they +//! could point to. + +use std::path::Path; + +use compliance_core::error::CoreError; +use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind}; +use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput}; +use tree_sitter::Node; + +use super::common::{parse, text, walk, FileGraph}; + +/// Base types whose methods a web framework calls: MVC and API +/// controllers, Razor pages, SignalR hubs, Web Forms pages, controls and +/// master pages, and ASMX services. +const WEB_BASES: [&str; 9] = [ + "Controller", + "ControllerBase", + "ApiController", + "PageModel", + "Hub", + "Page", + "UserControl", + "MasterPage", + "WebService", +]; + +/// Attributes that expose a method over HTTP. +const ENDPOINT_ATTRIBUTES: [&str; 10] = [ + "HttpGet", + "HttpPost", + "HttpPut", + "HttpDelete", + "HttpPatch", + "HttpHead", + "HttpOptions", + "AcceptVerbs", + "Route", + "WebMethod", +]; + +/// Parses C# sources. +#[derive(Debug, Default)] +pub struct CSharpParser; + +/// What a method's entry-point rule needs to know about its type. +#[derive(Clone, Copy)] +struct TypeContext<'a> { + qualified: &'a str, + /// The type derives from a web framework base or is an `[ApiController]`. + web: bool, + /// The type implements `IHttpHandler`, whose `ProcessRequest` the server calls. + http_handler: bool, +} + +impl CSharpParser { + /// A C# parser. + pub fn new() -> Self { + Self + } + + /// Visit type declarations at file level, in namespaces (block and + /// file-scoped alike), and nested in other types. + fn declarations( + root: Node<'_>, + parent: Option>, + source: &str, + graph: &mut FileGraph<'_>, + ) { + walk(root, |node| { + if node == root { + return true; + } + match node.kind() { + "class_declaration" + | "struct_declaration" + | "interface_declaration" + | "record_declaration" + | "enum_declaration" => { + Self::type_declaration(node, parent, source, graph); + false + } + "method_declaration" | "constructor_declaration" => { + if let Some(ty) = parent { + Self::method(node, ty, source, graph); + } + false + } + "compilation_unit" | "namespace_declaration" | "declaration_list" => true, + _ => false, + } + }); + } + + fn type_declaration( + node: Node<'_>, + parent: Option>, + source: &str, + graph: &mut FileGraph<'_>, + ) { + let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else { + return; + }; + let qualified = match parent { + Some(p) => format!("{}.{name}", p.qualified), + None => graph.top_level(name), + }; + let kind = match node.kind() { + "struct_declaration" => CodeNodeKind::Struct, + "interface_declaration" => CodeNodeKind::Interface, + "enum_declaration" => CodeNodeKind::Enum, + _ => CodeNodeKind::Class, + }; + graph.node(qualified.clone(), name, kind, node, false); + + let bases = base_types(node, source); + for (base, at) in &bases { + let edge = if is_interface_name(base) { + CodeEdgeKind::Implements + } else { + CodeEdgeKind::Inherits + }; + graph.edge(&qualified, base, edge, *at); + } + + let context = TypeContext { + qualified: &qualified, + web: bases.iter().any(|(b, _)| WEB_BASES.contains(b)) + || attributes(node, source).any(|a| a == "ApiController"), + http_handler: bases.iter().any(|(b, _)| *b == "IHttpHandler"), + }; + if let Some(body) = node.child_by_field_name("body") { + Self::declarations(body, Some(context), source, graph); + } + } + + fn method(node: Node<'_>, ty: TypeContext<'_>, source: &str, graph: &mut FileGraph<'_>) { + let Some(name) = node.child_by_field_name("name").map(|n| text(n, source)) else { + return; + }; + let qualified = format!("{}.{name}", ty.qualified); + let is_entry = + node.kind() == "method_declaration" && is_entry_point(node, name, ty, source); + graph.node( + qualified.clone(), + name, + CodeNodeKind::Method, + node, + is_entry, + ); + if let Some(body) = node.child_by_field_name("body") { + Self::calls(body, &qualified, source, graph); + } + } + + /// Calls by method name (`repo.Find(id)` calls `Find`) and constructions + /// (`new OrderDto(o)` calls `OrderDto`). + fn calls(body: Node<'_>, caller: &str, source: &str, graph: &mut FileGraph<'_>) { + walk(body, |node| { + let callee = match node.kind() { + "invocation_expression" => { + node.child_by_field_name("function").and_then(simple_name) + } + "object_creation_expression" => { + node.child_by_field_name("type").and_then(simple_name) + } + _ => None, + }; + if let Some(callee) = callee { + graph.edge(caller, text(callee, source), CodeEdgeKind::Calls, node); + } + true + }); + } +} + +/// Whether the framework, not our own code, calls this method. +fn is_entry_point(method: Node<'_>, name: &str, ty: TypeContext<'_>, source: &str) -> bool { + let mut cursor = method.walk(); + let modifiers: Vec<&str> = method + .children(&mut cursor) + .filter(|c| c.kind() == "modifier") + .map(|c| text(c, source)) + .collect(); + let has_modifier = |wanted: &str| modifiers.contains(&wanted); + if name == "Main" && has_modifier("static") { + return true; + } + if attributes(method, source).any(|a| ENDPOINT_ATTRIBUTES.contains(&a)) { + return true; + } + if ty.http_handler && name == "ProcessRequest" { + return true; + } + // Controller actions are public. Web Forms event handlers such as + // `Page_Load` or `BtnSave_Click` are usually protected; the markup + // wires them up. + ty.web && (has_modifier("public") || has_modifier("protected")) +} + +/// The simple names of a declaration's attributes, without namespace or +/// the `Attribute` suffix: `[System.Web.Services.WebMethodAttribute]` is +/// `WebMethod`. +fn attributes<'s>(declaration: Node<'_>, source: &'s str) -> impl Iterator { + let mut names = Vec::new(); + let mut cursor = declaration.walk(); + for list in declaration + .children(&mut cursor) + .filter(|c| c.kind() == "attribute_list") + { + let mut inner = list.walk(); + for attribute in list.named_children(&mut inner) { + if let Some(name) = attribute.child_by_field_name("name").and_then(simple_name) { + let name = text(name, source); + names.push(name.strip_suffix("Attribute").unwrap_or(name)); + } + } + } + names.into_iter() +} + +/// The simple names of the types in a declaration's base list, with the +/// node each one was named at. +fn base_types<'t, 's>(declaration: Node<'t>, source: &'s str) -> Vec<(&'s str, Node<'t>)> { + let mut cursor = declaration.walk(); + let Some(list) = declaration + .children(&mut cursor) + .find(|c| c.kind() == "base_list") + else { + return Vec::new(); + }; + let mut inner = list.walk(); + list.named_children(&mut inner) + .filter_map(|ty| simple_name(ty).map(|n| (text(n, source), ty))) + .collect() +} + +/// The last identifier of a name: `System.Web.UI.Page` is `Page`, +/// `List` is `List`, `repo.Find` is `Find`. +fn simple_name(node: Node<'_>) -> Option> { + match node.kind() { + "identifier" => Some(node), + "qualified_name" | "member_access_expression" => { + node.child_by_field_name("name").and_then(simple_name) + } + "generic_name" => node.named_child(0).filter(|n| n.kind() == "identifier"), + _ => None, + } +} + +/// .NET names interfaces `IName`; the base list doesn't say which base is +/// the class and which are interfaces, so the convention decides. +fn is_interface_name(name: &str) -> bool { + let mut chars = name.chars(); + chars.next() == Some('I') && chars.next().is_some_and(|c| c.is_ascii_uppercase()) +} + +impl LanguageParser for CSharpParser { + fn language(&self) -> &str { + "csharp" + } + + fn extensions(&self) -> &[&str] { + &["cs"] + } + + fn parse_file( + &self, + file_path: &Path, + source: &str, + repo_id: &str, + graph_build_id: &str, + ) -> Result { + let tree = parse(tree_sitter_c_sharp::LANGUAGE.into(), source, "C#")?; + let mut graph = FileGraph::new(file_path, source, repo_id, graph_build_id, "csharp"); + Self::declarations(tree.root_node(), None, source, &mut graph); + Ok(graph.finish()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + use compliance_core::models::graph::CodeNode; + + const WEB_APP: &str = r#" +using System; +using Microsoft.AspNetCore.Mvc; +namespace Plant.Web.Controllers { + [ApiController] + [Route("api/[controller]")] + public class OrdersController : ControllerBase, IDisposable { + private readonly IRepo _repo; + public OrdersController(IRepo repo) { _repo = repo; } + [HttpGet("{id}")] + public IActionResult Get(int id) { var o = _repo.Find(id); Log(o); return Ok(new OrderDto(o)); } + private void Log(object o) { Console.WriteLine(o); } + public void Dispose() {} + public class Nested { public void Inner() {} } + } + public interface IRepo { Order Find(int id); } + public struct Pt { public int X; } + public enum Kind { A, B } + public record OrderDto(Order O); + public class Repo : IRepo { public Order Find(int id) { return null; } } +} +namespace Other; +public partial class Default : System.Web.UI.Page { + protected void Page_Load(object sender, EventArgs e) { Bind(); } + private void Bind() { } + [System.Web.Services.WebMethodAttribute] public static string Ping() => "pong"; +} +public class Download : IHttpHandler { public void ProcessRequest(HttpContext c) { } } +public static class Program { static async Task Main(string[] args) { await Run(); } } +"#; + + fn parsed() -> ParseOutput { + CSharpParser::new() + .parse_file(Path::new("Web/Orders.cs"), WEB_APP, "repo", "build") + .expect("C# parses") + } + + fn node<'a>(out: &'a ParseOutput, qualified: &str) -> &'a CodeNode { + let qualified = format!("Web/Orders.cs::{qualified}"); + out.nodes + .iter() + .find(|n| n.qualified_name == qualified) + .unwrap_or_else(|| panic!("no node {qualified}")) + } + + #[test] + fn types_and_methods_become_nodes_in_every_namespace_form() { + let out = parsed(); + assert!(matches!( + node(&out, "OrdersController").kind, + CodeNodeKind::Class + )); + assert!(matches!(node(&out, "IRepo").kind, CodeNodeKind::Interface)); + assert!(matches!(node(&out, "Pt").kind, CodeNodeKind::Struct)); + assert!(matches!(node(&out, "Kind").kind, CodeNodeKind::Enum)); + assert!(matches!(node(&out, "OrderDto").kind, CodeNodeKind::Class)); + // A file-scoped namespace's types are siblings of its declaration. + assert!(matches!(node(&out, "Default").kind, CodeNodeKind::Class)); + for method in [ + "OrdersController.OrdersController", + "OrdersController.Get", + "OrdersController.Log", + "OrdersController.Nested.Inner", + "IRepo.Find", + "Default.Page_Load", + ] { + assert!( + matches!(node(&out, method).kind, CodeNodeKind::Method), + "{method}" + ); + } + } + + #[test] + fn framework_called_methods_are_entry_points() { + let out = parsed(); + for entry in [ + "OrdersController.Get", + "OrdersController.Dispose", + "Default.Page_Load", + "Default.Ping", + "Download.ProcessRequest", + "Program.Main", + ] { + assert!( + node(&out, entry).is_entry_point, + "{entry} is an entry point" + ); + } + for internal in [ + "OrdersController.Log", + "OrdersController.OrdersController", + "OrdersController.Nested.Inner", + "Default.Bind", + "Repo.Find", + ] { + assert!(!node(&out, internal).is_entry_point, "{internal} is not"); + } + } + + #[test] + fn bases_and_calls_become_edges() { + let out = parsed(); + let edges: Vec<(&str, &str, &str)> = out + .edges + .iter() + .map(|e| { + let kind = match e.kind { + CodeEdgeKind::Calls => "calls", + CodeEdgeKind::Inherits => "inherits", + CodeEdgeKind::Implements => "implements", + _ => "other", + }; + (kind, e.source.as_str(), e.target.as_str()) + }) + .collect(); + let controller = "Web/Orders.cs::OrdersController"; + assert!(edges.contains(&("inherits", controller, "ControllerBase"))); + assert!(edges.contains(&("implements", controller, "IDisposable"))); + assert!(edges.contains(&("inherits", "Web/Orders.cs::Default", "Page"))); + let get = "Web/Orders.cs::OrdersController.Get"; + for callee in ["Find", "Log", "Ok", "OrderDto"] { + assert!( + edges.contains(&("calls", get, callee)), + "Get calls {callee}" + ); + } + assert!(edges.contains(&("calls", "Web/Orders.cs::Program.Main", "Run"))); + } + + #[test] + fn overloads_share_one_node_and_keep_all_their_calls() { + let source = r#" +public class Orders : ControllerBase { + private void Find(int id) { ById(id); } + [HttpGet] public void Find(string name) { ByName(name); } +} +"#; + let out = CSharpParser::new() + .parse_file(Path::new("O.cs"), source, "r", "b") + .expect("C# parses"); + let finds: Vec<&CodeNode> = out + .nodes + .iter() + .filter(|n| n.qualified_name == "O.cs::Orders.Find") + .collect(); + assert_eq!(finds.len(), 1); + assert!(finds[0].is_entry_point, "one overload is an endpoint"); + let callees: Vec<&str> = out + .edges + .iter() + .filter(|e| e.source == "O.cs::Orders.Find") + .map(|e| e.target.as_str()) + .collect(); + assert_eq!(callees, ["ById", "ByName"]); + } + + #[test] + fn interface_names_follow_the_dotnet_convention() { + assert!(is_interface_name("IRepo")); + assert!(!is_interface_name("Item")); + assert!(!is_interface_name("I")); + } +} diff --git a/compliance-graph/src/parsers/mod.rs b/compliance-graph/src/parsers/mod.rs index e14b8e7..7b41cc6 100644 --- a/compliance-graph/src/parsers/mod.rs +++ b/compliance-graph/src/parsers/mod.rs @@ -1,3 +1,6 @@ +pub mod c; +mod common; +pub mod csharp; pub mod javascript; pub mod python; pub mod registry; diff --git a/compliance-graph/src/parsers/registry.rs b/compliance-graph/src/parsers/registry.rs index ed834ea..2846b74 100644 --- a/compliance-graph/src/parsers/registry.rs +++ b/compliance-graph/src/parsers/registry.rs @@ -5,6 +5,8 @@ use compliance_core::error::CoreError; use compliance_core::traits::graph_builder::{LanguageParser, ParseOutput}; use tracing::{debug, info}; +use super::c::CParser; +use super::csharp::CSharpParser; use super::javascript::JavaScriptParser; use super::python::PythonParser; use super::rust_parser::RustParser; @@ -24,6 +26,8 @@ impl ParserRegistry { Box::new(PythonParser::new()), Box::new(JavaScriptParser::new()), Box::new(TypeScriptParser::new()), + Box::new(CParser::new()), + Box::new(CSharpParser::new()), ]; let mut extension_map = HashMap::new(); diff --git a/compliance-graph/src/parsers/rust_parser.rs b/compliance-graph/src/parsers/rust_parser.rs index 9936c17..6a909da 100644 --- a/compliance-graph/src/parsers/rust_parser.rs +++ b/compliance-graph/src/parsers/rust_parser.rs @@ -363,6 +363,69 @@ impl RustParser { } } +impl LanguageParser for RustParser { + fn language(&self) -> &str { + "rust" + } + + fn extensions(&self) -> &[&str] { + &["rs"] + } + + fn parse_file( + &self, + file_path: &Path, + source: &str, + repo_id: &str, + graph_build_id: &str, + ) -> Result { + let mut parser = Parser::new(); + let language = tree_sitter_rust::LANGUAGE; + parser + .set_language(&language.into()) + .map_err(|e| CoreError::Graph(format!("Failed to set Rust language: {e}")))?; + + let tree = parser + .parse(source, None) + .ok_or_else(|| CoreError::Graph("Failed to parse Rust file".to_string()))?; + + let file_path_str = file_path.to_string_lossy().to_string(); + let mut output = ParseOutput::default(); + + // Add file node + output.nodes.push(CodeNode { + id: None, + repo_id: repo_id.to_string(), + graph_build_id: graph_build_id.to_string(), + qualified_name: file_path_str.clone(), + name: file_path + .file_name() + .map(|n| n.to_string_lossy().to_string()) + .unwrap_or_default(), + kind: CodeNodeKind::File, + file_path: file_path_str.clone(), + start_line: 1, + end_line: source.lines().count() as u32, + language: "rust".to_string(), + community_id: None, + is_entry_point: false, + graph_index: None, + }); + + self.walk_tree( + tree.root_node(), + source, + &file_path_str, + repo_id, + graph_build_id, + None, + &mut output, + ); + + Ok(output) + } +} + #[cfg(test)] mod tests { use super::*; @@ -570,66 +633,3 @@ mod tests { assert_eq!(parser.extensions(), &["rs"]); } } - -impl LanguageParser for RustParser { - fn language(&self) -> &str { - "rust" - } - - fn extensions(&self) -> &[&str] { - &["rs"] - } - - fn parse_file( - &self, - file_path: &Path, - source: &str, - repo_id: &str, - graph_build_id: &str, - ) -> Result { - let mut parser = Parser::new(); - let language = tree_sitter_rust::LANGUAGE; - parser - .set_language(&language.into()) - .map_err(|e| CoreError::Graph(format!("Failed to set Rust language: {e}")))?; - - let tree = parser - .parse(source, None) - .ok_or_else(|| CoreError::Graph("Failed to parse Rust file".to_string()))?; - - let file_path_str = file_path.to_string_lossy().to_string(); - let mut output = ParseOutput::default(); - - // Add file node - output.nodes.push(CodeNode { - id: None, - repo_id: repo_id.to_string(), - graph_build_id: graph_build_id.to_string(), - qualified_name: file_path_str.clone(), - name: file_path - .file_name() - .map(|n| n.to_string_lossy().to_string()) - .unwrap_or_default(), - kind: CodeNodeKind::File, - file_path: file_path_str.clone(), - start_line: 1, - end_line: source.lines().count() as u32, - language: "rust".to_string(), - community_id: None, - is_entry_point: false, - graph_index: None, - }); - - self.walk_tree( - tree.root_node(), - source, - &file_path_str, - repo_id, - graph_build_id, - None, - &mut output, - ); - - Ok(output) - } -}