feat(graph): PLC programs, function blocks and functions in the code graph (t82)
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m2s
CI / Check (pull_request) Successful in 20m29s
CI / Check (push) Skipped
CI / Detect Changes (pull_request) Skipped
CI / Deploy Agent (pull_request) Skipped
CI / Deploy Dashboard (pull_request) Skipped
CI / Deploy Docs (pull_request) Skipped
CI / Deploy MCP (pull_request) Skipped
CI / Agent integration (pull_request) Successful in 4m2s
CI / Check (pull_request) Successful in 20m29s
A PLC target now gets a code graph. Before this, PLC targets skipped the graph phase entirely. Nodes: - A PROGRAM is a module and an entry point. - A FUNCTION_BLOCK is a class. - A FUNCTION is a function. Edges: - A variable whose type is a function block is a type reference to it. - A call through an instance is a call to its type. - Calls by name are calls. - Standard blocks such as TON have no node, so their edges are dropped. How it fits together: - The PLC module reads each tree once, and both the findings and the graph come from that read. - The engine gets a public assemble step for nodes parsed outside the graph crate, and FileGraph is public with line-based adders. - One build function takes a tree or a PLC project's POUs. The scan uses it, and so does the explorer's manual rebuild, which would otherwise replace a PLC target's graph with file nodes only. POU spans: - A POU records the line of its END_ keyword. - A PLCopen POU spans its <pou> element in the XML. Its statements keep their synthetic lines, so finding lines and fingerprints don't change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
1569100721
commit
dc2c9845fd
14 files changed
+650
-61
No files matched your search
@@ -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;
|
||||
|
||||
@@ -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<GraphContext, AgentError> {
|
||||
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<GraphContext, AgentError> {
|
||||
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,
|
||||
);
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<SbomEntry> = 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
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
@@ -14,8 +14,96 @@ pub struct Pou {
|
||||
pub vars: Vec<VarDecl>,
|
||||
/// The statement body.
|
||||
pub body: Vec<Stmt>,
|
||||
/// 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 `<pou>` 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 `</pou>` 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 {
|
||||
|
||||
@@ -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<String, &str> = 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#"<?xml version="1.0" encoding="utf-8"?>
|
||||
<project>
|
||||
<types>
|
||||
<pous>
|
||||
<pou name="Main" pouType="program">
|
||||
<interface>
|
||||
<localVars>
|
||||
<variable name="pump1"><type><derived name="FB_Pump"/></type></variable>
|
||||
</localVars>
|
||||
</interface>
|
||||
<body>
|
||||
<ST><xhtml xmlns="http://www.w3.org/1999/xhtml">pump1(Start := TRUE);</xhtml></ST>
|
||||
</body>
|
||||
</pou>
|
||||
</pous>
|
||||
</types>
|
||||
</project>
|
||||
"#;
|
||||
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(""));
|
||||
}
|
||||
}
|
||||
@@ -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<Finding> {
|
||||
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<ast::Pou>,
|
||||
}
|
||||
|
||||
/// 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<PlcFile> {
|
||||
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<Finding> {
|
||||
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<Finding> {
|
||||
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<Finding> {
|
||||
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<Finding> {
|
||||
findings
|
||||
}
|
||||
|
||||
/// Walk a PLC project tree and produce findings.
|
||||
pub(crate) fn analyze_tree(root: &Path, repo_id: &str) -> Vec<Finding> {
|
||||
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 {
|
||||
|
||||
@@ -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,
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
@@ -49,7 +49,16 @@ pub fn parse_plcopen(xml: &str) -> Vec<Pou> {
|
||||
_ => "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
|
||||
// `<pou>` 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
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -238,7 +238,13 @@ impl LanguageParser for CParser {
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
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())
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -278,7 +278,13 @@ impl LanguageParser for CSharpParser {
|
||||
graph_build_id: &str,
|
||||
) -> Result<ParseOutput, CoreError> {
|
||||
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())
|
||||
}
|
||||
|
||||
@@ -6,3 +6,5 @@ pub mod python;
|
||||
pub mod registry;
|
||||
pub mod rust_parser;
|
||||
pub mod typescript;
|
||||
|
||||
pub use common::FileGraph;
|
||||
Reference in new issue
Block a user