diff --git a/compliance-agent/src/api/handlers/graph.rs b/compliance-agent/src/api/handlers/graph.rs index 5ca1d85..fe81abe 100644 --- a/compliance-agent/src/api/handlers/graph.rs +++ b/compliance-agent/src/api/handlers/graph.rs @@ -434,10 +434,17 @@ pub async fn trigger_build( } }; + // A PLC target's graph is its POUs, as the scan builds it. + let plc_files = crate::pipeline::plan::build_scan_plan(&repo) + .has(compliance_core::models::ScanType::PlcControlLogic) + .then(|| crate::pipeline::plc::read_tree(&repo_path)); + let source = match &plc_files { + Some(files) => crate::pipeline::graph_build::GraphSource::Plc(files), + None => crate::pipeline::graph_build::GraphSource::Tree(&repo_path), + }; let graph_build_id = uuid::Uuid::new_v4().to_string(); - let engine = compliance_graph::GraphEngine::new(50_000); - match engine.build_graph(&repo_path, &repo_id, &graph_build_id) { + match crate::pipeline::graph_build::build_graph(source, &repo_id, &graph_build_id) { Ok((code_graph, build_run)) => { let store = compliance_graph::graph::persistence::GraphStore::new(db.inner()); let _ = store.delete_repo_graph(&repo_id).await; diff --git a/compliance-agent/src/pipeline/graph_build.rs b/compliance-agent/src/pipeline/graph_build.rs index 53d9e17..79b6881 100644 --- a/compliance-agent/src/pipeline/graph_build.rs +++ b/compliance-agent/src/pipeline/graph_build.rs @@ -1,25 +1,71 @@ +use std::path::Path; + +use compliance_core::error::CoreError; +use compliance_core::models::graph::GraphBuildRun; use compliance_core::models::Finding; +use compliance_graph::graph::engine::CodeGraph; use super::orchestrator::{GraphContext, PipelineOrchestrator}; +use super::plc::PlcFile; use crate::error::AgentError; +/// The most nodes a graph build parses. +const GRAPH_MAX_NODES: u32 = 50_000; + +/// What a code graph is built from. +pub(crate) enum GraphSource<'a> { + /// The source files of a checked-out tree, by the graph crate's parsers. + Tree(&'a Path), + /// The POUs of a PLC target, read from every one of its PLC source trees. + Plc(&'a [PlcFile]), +} + +/// Build a code graph and detect its communities. +/// +/// # Errors +/// +/// Returns the graph engine's error when a tree can't be read or the graph +/// can't be assembled. +pub(crate) fn build_graph( + source: GraphSource<'_>, + repo_id: &str, + graph_build_id: &str, +) -> Result<(CodeGraph, GraphBuildRun), CoreError> { + let engine = compliance_graph::GraphEngine::new(GRAPH_MAX_NODES); + match source { + GraphSource::Tree(path) => engine.build_graph(path, repo_id, graph_build_id), + GraphSource::Plc(files) => engine.assemble( + super::plc::graph::parse_output(files, repo_id, graph_build_id), + repo_id, + ), + } +} + impl PipelineOrchestrator { - /// Build the code knowledge graph for a repo and compute impact analyses + /// Build the code knowledge graph for a repo, store it in place of the + /// previous one and compute the impact of each finding. pub(super) async fn build_code_graph( &self, - repo_path: &std::path::Path, + source: GraphSource<'_>, repo_id: &str, findings: &[Finding], ) -> Result { let graph_build_id = uuid::Uuid::new_v4().to_string(); - let engine = compliance_graph::GraphEngine::new(50_000); - - // The build assigns communities too. - let (code_graph, build_run) = engine - .build_graph(repo_path, repo_id, &graph_build_id) + let built = build_graph(source, repo_id, &graph_build_id) .map_err(|e| AgentError::Other(format!("Graph build error: {e}")))?; + self.store_code_graph(built, repo_id, &graph_build_id, findings) + .await + } - // Store graph in MongoDB + /// Replace the repo's stored graph with `built`, and store the impact of + /// each finding that has a file. + async fn store_code_graph( + &self, + (code_graph, build_run): (CodeGraph, GraphBuildRun), + repo_id: &str, + graph_build_id: &str, + findings: &[Finding], + ) -> Result { let store = compliance_graph::graph::persistence::GraphStore::new(self.db.inner()); store .delete_repo_graph(repo_id) @@ -39,7 +85,7 @@ impl PipelineOrchestrator { let impact = analyzer.analyze( repo_id, &finding.fingerprint, - &graph_build_id, + graph_build_id, file_path, finding.line_number, ); diff --git a/compliance-agent/src/pipeline/mod.rs b/compliance-agent/src/pipeline/mod.rs index 8e65f46..85eb6b7 100644 --- a/compliance-agent/src/pipeline/mod.rs +++ b/compliance-agent/src/pipeline/mod.rs @@ -23,7 +23,7 @@ pub mod git; pub mod git_retry; pub mod git_submodules; pub mod gitleaks; -mod graph_build; +pub(crate) mod graph_build; pub mod grouping; pub mod ios_config; mod issue_catchup; diff --git a/compliance-agent/src/pipeline/orchestrator.rs b/compliance-agent/src/pipeline/orchestrator.rs index 1606765..847e801 100644 --- a/compliance-agent/src/pipeline/orchestrator.rs +++ b/compliance-agent/src/pipeline/orchestrator.rs @@ -938,8 +938,12 @@ impl PipelineOrchestrator { self.update_phase(scan_run_id, ScanPhase::GraphBuilding) .await; let graph_context = match async { - self.build_code_graph(&repo_path, &repo_id, &all_findings) - .await + self.build_code_graph( + crate::pipeline::graph_build::GraphSource::Tree(&repo_path), + &repo_id, + &all_findings, + ) + .await } .instrument(tracing::info_span!("stage_graph_building")) .await @@ -1723,6 +1727,8 @@ impl PipelineOrchestrator { // Each source's findings next to the tree they were found in: the // control mapping below reads the flagged regions from it. let mut analysed = Vec::with_capacity(sources.len()); + // Every tree's POUs, for the code graph. + let mut plc_files = Vec::new(); let mut all_sbom: Vec = Vec::new(); let mut sbom_seen = std::collections::BTreeSet::new(); // CODESYS projects in their native format: their control logic is not @@ -1741,10 +1747,12 @@ impl PipelineOrchestrator { left_out.excluded.extend(pruned.excluded); left_out.test_data.extend(pruned.test_data); native.extend(crate::pipeline::plc::native_projects(&path)); + let files = crate::pipeline::plc::read_tree(&path); analysed.push(( path.clone(), - crate::pipeline::plc::analyze_tree(&path, target_id), + crate::pipeline::plc::findings(&files, target_id), )); + plc_files.extend(files); // Control-application SBOM: CODESYS libraries + runtime from a // `.projectarchive` (uploaded, or committed in the working tree). let archive = a @@ -1806,6 +1814,21 @@ impl PipelineOrchestrator { "PLC control-logic analysis complete" ); + // The POUs and how they use each other, as for a code scan; a stale + // graph is replaced even when no POU was read. + self.update_phase(scan_run_id, ScanPhase::GraphBuilding) + .await; + if let Err(e) = self + .build_code_graph( + crate::pipeline::graph_build::GraphSource::Plc(&plc_files), + target_id, + &all_findings, + ) + .await + { + tracing::warn!(target_id, error = %e, "PLC graph building failed"); + } + let mut new_count = 0u32; let mut refreshed_count = 0u32; for mut finding in all_findings { @@ -3258,6 +3281,7 @@ fn planned_phases( if config.breakpilot.semantic_mapping { phases.push(ScanPhase::SemanticControlMapping); } + phases.push(ScanPhase::GraphBuilding); if config.plc_runtime.enabled && target.live_url().is_none() { phases.push(ScanPhase::PlcProvision); } @@ -3411,7 +3435,11 @@ mod tests { assert_eq!( planned_phases(&target, &plan, &config), - [ScanPhase::Classification, ScanPhase::PlcAnalysis] + [ + ScanPhase::Classification, + ScanPhase::PlcAnalysis, + ScanPhase::GraphBuilding + ] ); // The LLM control mapping is a phase of its own, so a long one shows. @@ -3421,7 +3449,8 @@ mod tests { [ ScanPhase::Classification, ScanPhase::PlcAnalysis, - ScanPhase::SemanticControlMapping + ScanPhase::SemanticControlMapping, + ScanPhase::GraphBuilding ] ); } diff --git a/compliance-agent/src/pipeline/plc/ast.rs b/compliance-agent/src/pipeline/plc/ast.rs index fd4ae3c..46360bc 100644 --- a/compliance-agent/src/pipeline/plc/ast.rs +++ b/compliance-agent/src/pipeline/plc/ast.rs @@ -14,8 +14,96 @@ pub struct Pou { pub vars: Vec, /// The statement body. pub body: Vec, - /// 1-based line where the POU header appears (in the source that was parsed). + /// 1-based line where the POU header appears. For a PLCopen POU it is + /// the `` element's line in the XML; its statements keep the lines + /// of the Structured Text reconstructed from it. pub line: u32, + /// 1-based line of its `END_*` keyword (the last line when it is + /// missing); for a PLCopen POU, the `` line. + pub end_line: u32, +} + +impl Pou { + /// Call `visit` with the callee and line of every call in the body, bare + /// (`TON1(IN := x);`) or inside an expression (`LIMIT(0, x, 10)`), in + /// source order. + pub fn for_each_call(&self, mut visit: impl FnMut(&str, u32)) { + for stmt in &self.body { + stmt.for_each_call(&mut visit); + } + } +} + +impl Stmt { + /// See [`Pou::for_each_call`]. `visit` is `&mut dyn` so the recursion + /// through nested blocks doesn't instantiate a new closure type per level. + fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) { + let block = |body: &[Stmt], visit: &mut dyn FnMut(&str, u32)| { + for stmt in body { + stmt.for_each_call(visit); + } + }; + match self { + Stmt::Assign { target, value, .. } => { + target.for_each_call(visit); + value.for_each_call(visit); + } + Stmt::If { + branches, + else_body, + .. + } => { + for (cond, body) in branches { + cond.for_each_call(visit); + block(body, visit); + } + if let Some(body) = else_body { + block(body, visit); + } + } + Stmt::Case { + selector, + arms, + else_body, + .. + } => { + selector.for_each_call(visit); + for (labels, body) in arms { + for label in labels { + label.for_each_call(visit); + } + block(body, visit); + } + if let Some(body) = else_body { + block(body, visit); + } + } + Stmt::For { + from, to, by, body, .. + } => { + from.for_each_call(visit); + to.for_each_call(visit); + if let Some(by) = by { + by.for_each_call(visit); + } + block(body, visit); + } + Stmt::While { cond, body, .. } + | Stmt::Repeat { + body, until: cond, .. + } => { + cond.for_each_call(visit); + block(body, visit); + } + Stmt::Call { callee, args, line } => { + visit(callee, *line); + for arg in args { + arg.value.for_each_call(visit); + } + } + Stmt::Return { .. } | Stmt::Exit { .. } | Stmt::Jump { .. } | Stmt::Label { .. } => {} + } + } } #[derive(Debug, Clone, Copy, PartialEq, Eq)] @@ -191,6 +279,35 @@ impl Expr { } } + /// See [`Pou::for_each_call`]. + fn for_each_call(&self, visit: &mut dyn FnMut(&str, u32)) { + match self { + Expr::Int(..) + | Expr::Real(..) + | Expr::Bool(..) + | Expr::Str(..) + | Expr::Time(..) + | Expr::Ident(..) => {} + Expr::Index { base, index, .. } => { + base.for_each_call(visit); + index.for_each_call(visit); + } + Expr::Member { base, .. } | Expr::Unary { expr: base, .. } => { + base.for_each_call(visit); + } + Expr::Binary { lhs, rhs, .. } => { + lhs.for_each_call(visit); + rhs.for_each_call(visit); + } + Expr::Call { callee, args, line } => { + visit(callee, *line); + for arg in args { + arg.value.for_each_call(visit); + } + } + } + } + /// If this expression is a plain identifier, its name. pub fn as_ident(&self) -> Option<&str> { match self { diff --git a/compliance-agent/src/pipeline/plc/graph.rs b/compliance-agent/src/pipeline/plc/graph.rs new file mode 100644 index 0000000..20e94dc --- /dev/null +++ b/compliance-agent/src/pipeline/plc/graph.rs @@ -0,0 +1,295 @@ +//! The POUs of a PLC project as code-graph nodes and edges, for +//! [`compliance_graph::GraphEngine::assemble`]. +//! +//! - A `PROGRAM` is a module and an entry point: the PLC's tasks run it. +//! - A `FUNCTION_BLOCK` is a class, since each instance keeps its own state. +//! - A `FUNCTION` is a function. +//! +//! A variable whose type is a function block is a dependency on it (a type +//! reference). A call through an instance (`Pump1(Start := x)`) is a call to +//! its type. Standard blocks such as `TON` or `CTU` have no node, so their +//! edges stay unresolved and the engine drops them. + +use std::collections::HashMap; +use std::path::Path; + +use compliance_core::models::graph::{CodeEdgeKind, CodeNodeKind}; +use compliance_core::traits::graph_builder::ParseOutput; +use compliance_graph::parsers::FileGraph; + +use super::ast::{Pou, PouKind}; +use super::PlcFile; + +/// The nodes and edges of every POU in `files`. +/// +/// # Arguments +/// +/// * `files` - the PLC source files read from one or more trees +/// * `repo_id`, `graph_build_id` - stamped on every node and edge +pub(crate) fn parse_output(files: &[PlcFile], repo_id: &str, graph_build_id: &str) -> ParseOutput { + let mut output = ParseOutput::default(); + for file in files { + let language = if file.plcopen { + "plcopen" + } else { + "structured_text" + }; + let mut graph = FileGraph::new( + Path::new(&file.rel), + file.line_count, + repo_id, + graph_build_id, + language, + ); + for pou in &file.pous { + add_pou(&mut graph, pou); + } + let part = graph.finish(); + output.nodes.extend(part.nodes); + output.edges.extend(part.edges); + } + output +} + +/// Add `pou`'s node, its type references and its calls. +fn add_pou(graph: &mut FileGraph<'_>, pou: &Pou) { + let qualified = graph.top_level(&pou.name); + let kind = match pou.kind { + PouKind::Program => CodeNodeKind::Module, + PouKind::FunctionBlock => CodeNodeKind::Class, + PouKind::Function => CodeNodeKind::Function, + }; + graph.node_at( + qualified.clone(), + pou.name.clone(), + kind, + (pou.line, pou.end_line), + pou.kind == PouKind::Program, + ); + + // IEC 61131-3 identifiers are case-insensitive, so the instances are + // looked up by their lowercased name. + let mut instances: HashMap = HashMap::with_capacity(pou.vars.len()); + for var in &pou.vars { + if !is_identifier(&var.type_name) { + continue; // ARRAY[..] OF, POINTER TO, STRING(80): not a block type + } + graph.edge_at(&qualified, &var.type_name, CodeEdgeKind::TypeRef, var.line); + instances.insert(var.name.to_ascii_lowercase(), var.type_name.as_str()); + } + + pou.for_each_call(|callee, line| { + let target = instances + .get(&callee.to_ascii_lowercase()) + .copied() + .unwrap_or(callee); + graph.edge_at(&qualified, target, CodeEdgeKind::Calls, line); + }); +} + +/// Whether a declared type is a plain name (`FB_Pump`, `TON`, `INT`). +fn is_identifier(type_name: &str) -> bool { + !type_name.is_empty() + && type_name + .chars() + .all(|c| c.is_ascii_alphanumeric() || c == '_') +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::pipeline::plc::{parser, plcopen}; + + fn st_file(rel: &str, source: &str) -> PlcFile { + PlcFile { + rel: rel.to_string(), + plcopen: false, + line_count: source.lines().count() as u32, + pous: parser::parse(source), + } + } + + const LINE: &str = "\ +FUNCTION_BLOCK FB_Pump +VAR_INPUT + Start : BOOL; +END_VAR +VAR + Delay : TON; +END_VAR + Delay(IN := Start, PT := T#2s); +END_FUNCTION_BLOCK + +FUNCTION Clamp : INT +VAR_INPUT + x : INT; +END_VAR + Clamp := LIMIT(0, x, 100); +END_FUNCTION + +PROGRAM Main +VAR + pump1 : FB_Pump; + level : INT; +END_VAR + PUMP1(Start := TRUE); + IF Clamp(level) > 50 THEN + level := 0; + END_IF; +END_PROGRAM +"; + + #[test] + fn pous_become_nodes_and_programs_entry_points() { + let output = parse_output(&[st_file("src/line.st", LINE)], "r", "b"); + + let node = |name: &str| { + output + .nodes + .iter() + .find(|n| n.name == name) + .unwrap_or_else(|| panic!("no node {name}")) + }; + assert_eq!(node("line.st").kind, CodeNodeKind::File); + let pump = node("FB_Pump"); + assert_eq!(pump.kind, CodeNodeKind::Class); + assert_eq!(pump.qualified_name, "src/line.st::FB_Pump"); + assert_eq!((pump.start_line, pump.end_line), (1, 9)); + assert!(!pump.is_entry_point); + assert_eq!(node("Clamp").kind, CodeNodeKind::Function); + let main = node("Main"); + assert_eq!(main.kind, CodeNodeKind::Module); + assert_eq!((main.start_line, main.end_line), (18, 27)); + assert!(main.is_entry_point); + assert!(output.nodes.iter().all(|n| n.language == "structured_text")); + } + + #[test] + fn instances_lead_to_their_type_and_calls_to_the_callee() { + let output = parse_output(&[st_file("line.st", LINE)], "r", "b"); + let edges: Vec<(&str, CodeEdgeKind)> = output + .edges + .iter() + .filter(|e| e.source == "line.st::Main") + .map(|e| (e.target.as_str(), e.kind.clone())) + .collect(); + + // The instance declaration and the call through it (in another case) + // lead to FB_Pump; the function is called by name. + let to = |target: &str, kind: CodeEdgeKind| { + edges + .iter() + .filter(|(t, k)| *t == target && *k == kind) + .count() + }; + assert_eq!(to("FB_Pump", CodeEdgeKind::TypeRef), 1); + assert_eq!(to("FB_Pump", CodeEdgeKind::Calls), 1); + assert_eq!(to("Clamp", CodeEdgeKind::Calls), 1); + // A standard block keeps its own name and resolves to nothing. + assert!(output + .edges + .iter() + .any(|e| e.source == "line.st::FB_Pump" && e.target == "TON")); + } + + #[test] + fn plcopen_pous_span_their_xml_element() { + let xml = r#" + + + + + + + + + + + pump1(Start := TRUE); + + + + + +"#; + let file = PlcFile { + rel: "export.xml".to_string(), + plcopen: true, + line_count: xml.lines().count() as u32, + pous: plcopen::parse_plcopen(xml), + }; + let output = parse_output(&[file], "r", "b"); + + let main = output + .nodes + .iter() + .find(|n| n.name == "Main") + .expect("Main is a node"); + assert_eq!((main.start_line, main.end_line), (5, 14)); + assert_eq!(main.language, "plcopen"); + assert!(output + .edges + .iter() + .any(|e| e.target == "FB_Pump" && e.kind == CodeEdgeKind::Calls)); + } + + #[test] + fn the_engine_links_instances_and_drops_standard_blocks() { + let output = parse_output(&[st_file("line.st", LINE)], "r", "b"); + let (graph, run) = compliance_graph::GraphEngine::new(1_000) + .assemble(output, "r") + .expect("assembles"); + + let linked = |source: &str, target: &str| { + graph + .edges + .iter() + .any(|e| e.source == source && e.target == target) + }; + assert!(linked("line.st::Main", "line.st::FB_Pump")); + assert!(linked("line.st::Main", "line.st::Clamp")); + assert!(!graph.edges.iter().any(|e| e.target == "TON")); + assert_eq!(run.languages_parsed, ["structured_text"]); + } + + #[test] + fn every_pou_of_the_demo_project_is_a_node() { + let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("../examples/plc-demo"); + let mut files = crate::pipeline::plc::read_tree(&root); + files.sort_by(|a, b| a.rel.cmp(&b.rel)); + let output = parse_output(&files, "r", "b"); + + let mut pous: Vec<(&str, bool)> = output + .nodes + .iter() + .filter(|n| n.kind != CodeNodeKind::File) + .map(|n| (n.name.as_str(), n.is_entry_point)) + .collect(); + pous.sort(); + assert_eq!( + pous, + [ + ("ConveyorCtrl", true), + ("PumpFbdCtrl", false), + ("PumpStationCtrl", false), + ("TrafficLight", true), + ] + ); + assert_eq!( + output + .nodes + .iter() + .filter(|n| n.kind == CodeNodeKind::File) + .count(), + 4 + ); + } + + #[test] + fn only_plain_type_names_are_references() { + assert!(is_identifier("FB_Pump")); + assert!(!is_identifier("ARRAY[0..9] OF INT")); + assert!(!is_identifier("STRING(80)")); + assert!(!is_identifier("")); + } +} diff --git a/compliance-agent/src/pipeline/plc/mod.rs b/compliance-agent/src/pipeline/plc/mod.rs index 0707484..081467e 100644 --- a/compliance-agent/src/pipeline/plc/mod.rs +++ b/compliance-agent/src/pipeline/plc/mod.rs @@ -9,6 +9,7 @@ //! scan says so instead of finding nothing in silence (#165). pub mod ast; +pub(crate) mod graph; pub mod lexer; pub mod parser; pub mod plcopen; @@ -45,9 +46,21 @@ impl Scanner for PlcControlLogicScanner { } } -/// Walk a PLC project tree and produce findings. -pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { - let mut findings = Vec::new(); +/// A PLC source file and the POUs read from it. +pub(crate) struct PlcFile { + /// The path relative to the tree it was found in. + pub(crate) rel: String, + /// Whether it is a PLCopen XML export rather than Structured Text. + pub(crate) plcopen: bool, + /// Its number of lines. + pub(crate) line_count: u32, + pub(crate) pous: Vec, +} + +/// Read every PLC source file under `root` (Structured Text, and PLCopen XML +/// exports) into its POUs. Files with no POU are left out. +pub(crate) fn read_tree(root: &Path) -> Vec { + let mut files = Vec::new(); for entry in walkdir::WalkDir::new(root) .into_iter() .filter_map(|e| e.ok()) @@ -82,16 +95,34 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { if pous.is_empty() { continue; } - let rel = path - .strip_prefix(root) - .unwrap_or(path) - .to_string_lossy() - .to_string(); - for pou in &pous { + files.push(PlcFile { + rel: path + .strip_prefix(root) + .unwrap_or(path) + .to_string_lossy() + .to_string(), + plcopen: is_xml, + line_count: content.lines().count() as u32, + pous, + }); + } + files +} + +/// Run the control-logic rules over the POUs of `files`. +pub(crate) fn findings(files: &[PlcFile], repo_id: &str) -> Vec { + let mut findings = Vec::new(); + for file in files { + for pou in &file.pous { for hit in rules::analyze(pou) { let line_s = hit.line.to_string(); - let fingerprint = - dedup::compute_fingerprint(&[repo_id, &rel, hit.rule_id, &pou.name, &line_s]); + let fingerprint = dedup::compute_fingerprint(&[ + repo_id, + &file.rel, + hit.rule_id, + &pou.name, + &line_s, + ]); let mut f = Finding::new( repo_id.to_string(), fingerprint, @@ -101,7 +132,7 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { hit.description, hit.severity, ); - f.file_path = Some(rel.clone()); + f.file_path = Some(file.rel.clone()); f.line_number = Some(hit.line); f.rule_id = Some(hit.rule_id.to_string()); f.cwe = hit.cwe.map(String::from); @@ -113,6 +144,11 @@ pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { findings } +/// Walk a PLC project tree and produce findings. +pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec { + findings(&read_tree(root), repo_id) +} + /// Whether `content` starts as an XML document (after a byte-order mark and /// white space). fn looks_like_xml(content: &str) -> bool { diff --git a/compliance-agent/src/pipeline/plc/parser.rs b/compliance-agent/src/pipeline/plc/parser.rs index c90b3d8..e930c19 100644 --- a/compliance-agent/src/pipeline/plc/parser.rs +++ b/compliance-agent/src/pipeline/plc/parser.rs @@ -119,6 +119,7 @@ impl Parser { body.push(s); } } + let end_line = self.line(); self.eat_kw(end); Some(Pou { @@ -127,6 +128,7 @@ impl Parser { vars, body, line, + end_line, }) } diff --git a/compliance-agent/src/pipeline/plc/plcopen.rs b/compliance-agent/src/pipeline/plc/plcopen.rs index 7b6eaa0..ff84216 100644 --- a/compliance-agent/src/pipeline/plc/plcopen.rs +++ b/compliance-agent/src/pipeline/plc/plcopen.rs @@ -49,7 +49,16 @@ pub fn parse_plcopen(xml: &str) -> Vec { _ => "PROGRAM", }; let synthetic = format!("{kw} {name}\n{var_block}{body}\nEND_{kw}\n"); - pous.extend(parser::parse(&synthetic)); + // Statement lines stay those of the synthetic source (the findings' + // lines and fingerprints use them); the POU itself spans its + // `` element in the XML, which is what the code graph shows. + let start = doc.text_pos_at(pou.range().start).row; + let end = doc.text_pos_at(pou.range().end).row; + pous.extend(parser::parse(&synthetic).into_iter().map(|mut parsed| { + parsed.line = start; + parsed.end_line = end; + parsed + })); } pous } diff --git a/compliance-graph/src/graph/engine.rs b/compliance-graph/src/graph/engine.rs index e21ca60..3ec0d71 100644 --- a/compliance-graph/src/graph/engine.rs +++ b/compliance-graph/src/graph/engine.rs @@ -203,22 +203,37 @@ impl GraphEngine { repo_id: &str, graph_build_id: &str, ) -> Result<(CodeGraph, GraphBuildRun), CoreError> { - let mut build_run = GraphBuildRun::new(repo_id.to_string()); - info!(repo_id, path = %repo_path.display(), "Starting graph build"); - - // Phase 1: Parse all files let parse_output = self.parser_registry.parse_directory( repo_path, repo_id, graph_build_id, self.max_nodes, )?; + self.assemble(parse_output, repo_id) + } - // Phase 2: Build petgraph + /// 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)?; - // Phase 3: Run community detection let community_count = apply_communities(&mut code_graph); // Collect language stats diff --git a/compliance-graph/src/parsers/c.rs b/compliance-graph/src/parsers/c.rs index 0cd4bc0..1b4d94f 100644 --- a/compliance-graph/src/parsers/c.rs +++ b/compliance-graph/src/parsers/c.rs @@ -238,7 +238,13 @@ impl LanguageParser for CParser { 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"); + let mut graph = FileGraph::new( + file_path, + source.lines().count() as u32, + 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()) diff --git a/compliance-graph/src/parsers/common.rs b/compliance-graph/src/parsers/common.rs index 61d3e43..9f1f0d8 100644 --- a/compliance-graph/src/parsers/common.rs +++ b/compliance-graph/src/parsers/common.rs @@ -62,8 +62,10 @@ pub(crate) fn walk(root: Node<'_>, mut visit: impl FnMut(Node<'_>) -> bool) { } /// The nodes and edges of one file, with the identifiers every one of them -/// carries filled in once. -pub(crate) struct FileGraph<'a> { +/// carries filled in once. The tree-sitter parsers use it, and so can a +/// parser outside this crate (the agent's IEC 61131-3 one), which hands the +/// result to [`crate::GraphEngine::assemble`]. +pub struct FileGraph<'a> { repo_id: &'a str, graph_build_id: &'a str, file_path: String, @@ -77,9 +79,16 @@ pub(crate) struct FileGraph<'a> { impl<'a> FileGraph<'a> { /// Start a file's graph with its `File` node. - pub(crate) fn new( + /// + /// # Arguments + /// + /// * `file_path` - the file's path relative to the scanned tree + /// * `line_count` - the file's number of lines, the `File` node's end line + /// * `repo_id`, `graph_build_id` - stamped on every node and edge + /// * `language` - the language name the nodes carry, e.g. `"c"` + pub fn new( file_path: &Path, - source: &str, + line_count: u32, repo_id: &'a str, graph_build_id: &'a str, language: &'static str, @@ -97,24 +106,27 @@ impl<'a> FileGraph<'a> { .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.node_at( + file_path_str, + name, + CodeNodeKind::File, + (1, line_count), + false, + ); graph } /// The file's path, which is also its `File` node's qualified name. - pub(crate) fn file_path(&self) -> &str { + pub 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 { + pub 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. + /// Add a declaration spanning the syntax node `node`; see [`Self::node_at`]. pub(crate) fn node( &mut self, qualified_name: String, @@ -124,27 +136,28 @@ impl<'a> FileGraph<'a> { is_entry_point: bool, ) { let end_line = node.end_position().row as u32 + 1; - self.push_node( + self.node_at( qualified_name, name.to_string(), kind, - line(node), - end_line, + (line(node), end_line), is_entry_point, ); } - fn push_node( + /// Add a declaration spanning `lines` (1-based start and end, inclusive). + /// 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, and an entry point makes it one. + pub fn node_at( &mut self, qualified_name: String, name: String, kind: CodeNodeKind, - start_line: u32, - end_line: u32, + (start_line, end_line): (u32, 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; } @@ -167,9 +180,15 @@ impl<'a> FileGraph<'a> { }); } - /// Add an edge from `source` to `target`, which the engine resolves - /// later (a bare name is fine). + /// Add an edge found at the syntax node `at`; see [`Self::edge_at`]. pub(crate) fn edge(&mut self, source: &str, target: &str, kind: CodeEdgeKind, at: Node<'_>) { + self.edge_at(source, target, kind, line(at)); + } + + /// Add an edge from `source` to `target`, found on `line`. The engine + /// resolves `target` later, so a bare name is fine; one that matches no + /// node is dropped. + pub fn edge_at(&mut self, source: &str, target: &str, kind: CodeEdgeKind, line: u32) { self.output.edges.push(CodeEdge { id: None, repo_id: self.repo_id.to_string(), @@ -178,12 +197,12 @@ impl<'a> FileGraph<'a> { target: target.to_string(), kind, file_path: self.file_path.clone(), - line_number: Some(line(at)), + line_number: Some(line), }); } /// The finished nodes and edges. - pub(crate) fn finish(self) -> ParseOutput { + pub fn finish(self) -> ParseOutput { self.output } } diff --git a/compliance-graph/src/parsers/csharp.rs b/compliance-graph/src/parsers/csharp.rs index 6066789..2809126 100644 --- a/compliance-graph/src/parsers/csharp.rs +++ b/compliance-graph/src/parsers/csharp.rs @@ -278,7 +278,13 @@ impl LanguageParser for CSharpParser { 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"); + let mut graph = FileGraph::new( + file_path, + source.lines().count() as u32, + repo_id, + graph_build_id, + "csharp", + ); Self::declarations(tree.root_node(), None, source, &mut graph); Ok(graph.finish()) } diff --git a/compliance-graph/src/parsers/mod.rs b/compliance-graph/src/parsers/mod.rs index 7b41cc6..8405305 100644 --- a/compliance-graph/src/parsers/mod.rs +++ b/compliance-graph/src/parsers/mod.rs @@ -6,3 +6,5 @@ pub mod python; pub mod registry; pub mod rust_parser; pub mod typescript; + +pub use common::FileGraph;