Skip to content

Commit 0dddf1e

Browse files
committed
feat: update version to 0.3.1, enhance PLCopen support, and improve error handling
- Bump version to 0.3.1 in Cargo.toml and Cargo.lock - Add detailed changelog entries for new features and fixes - Implement full support for graphical languages (FBD, LD, SFC) in analysis - Enhance error types with std::error::Error trait for better error handling - Improve extraction methods for variable references across all IEC 61131-3 languages
1 parent 3e25d6e commit 0dddf1e

13 files changed

Lines changed: 370 additions & 47 deletions

File tree

‎Cargo.lock‎

Lines changed: 1 addition & 1 deletion
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎plceye/CHANGELOG.md‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,24 @@
11
# Changelog
22

3+
## 0.7.1 (2025-12-14)
4+
5+
### Added
6+
- PLCopen graphical language support: FBD, LD, SFC reference extraction
7+
- PLCopen stats display with `--stats` option
8+
- Shows POU counts by type (Functions, Function Blocks, Programs)
9+
- Displays language usage across all 5 IEC 61131-3 languages
10+
- Variable counts and empty POU detection
11+
12+
### Fixed
13+
- Comment filtering in ST/IL code extraction (prevents false positives)
14+
- IL opcode recognition (prevents opcodes being flagged as undefined variables)
15+
- Improved identifier validation (rejects tokens with punctuation)
16+
- `--stats` now correctly displays PLCopen project statistics
17+
18+
### Changed
19+
- Enhanced variable reference extraction across all IEC 61131-3 languages
20+
- Better unused variable detection for graphical languages
21+
322
## 0.7.0 (2025-12-11)
423

524
### Changed

‎plceye/README.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,12 @@ A static analyzer and code smell detector for PLC files.
66

77
- **L5X** - Rockwell Automation Studio 5000 Logix Designer
88
- **PLCopen XML** - IEC 61131-3 standard exchange format
9+
- All 5 IEC 61131-3 languages supported:
10+
- ST (Structured Text)
11+
- IL (Instruction List)
12+
- FBD (Function Block Diagram)
13+
- LD (Ladder Diagram)
14+
- SFC (Sequential Function Chart)
915

1016
## Features
1117

@@ -45,6 +51,7 @@ plceye --severity warning project.L5X
4551

4652
# Show file statistics (no rule detection)
4753
plceye --stats project.L5X
54+
plceye --stats project.xml # PLCopen stats show language usage
4855

4956
# Generate default configuration
5057
plceye init

‎plceye/src/analysis/plcopen_analysis.rs‎

Lines changed: 135 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -262,12 +262,22 @@ fn extract_formatted_text(ft: &FormattedText) -> Option<String> {
262262
ft.text.clone()
263263
}
264264

265+
/// Extract variable and POU references from ST (Structured Text) code.
266+
///
267+
/// This function:
268+
/// - Removes comments (both `(* ... *)` and `//` style)
269+
/// - Splits code into identifiers
270+
/// - Filters out keywords and non-identifiers
271+
/// - Adds potential variable/POU references to the analysis
265272
fn extract_references_from_st(code: &str, analysis: &mut PlcopenAnalysis) {
273+
// Remove comments: (* ... *) and // ...
274+
let code = remove_plc_comments(code);
275+
266276
// Simple extraction: find identifiers that could be variables
267277
for word in code.split(|c: char| !c.is_alphanumeric() && c != '_') {
268278
let word = word.trim();
269279
if !word.is_empty()
270-
&& word.chars().next().map(|c| c.is_alphabetic()).unwrap_or(false)
280+
&& is_identifier(word)
271281
&& !is_st_keyword(word)
272282
{
273283
// Could be a variable or POU call
@@ -276,19 +286,45 @@ fn extract_references_from_st(code: &str, analysis: &mut PlcopenAnalysis) {
276286
}
277287
}
278288

289+
/// Extract variable references from IL (Instruction List) code.
290+
///
291+
/// This function:
292+
/// - Removes comments
293+
/// - Parses IL format: `OPCODE OPERAND`
294+
/// - Filters out IL opcodes (LD, ST, ADD, etc.)
295+
/// - Extracts operands as variable references
279296
fn extract_references_from_il(code: &str, analysis: &mut PlcopenAnalysis) {
297+
// Remove comments: (* ... *) and // ...
298+
let code = remove_plc_comments(code);
299+
280300
// IL format: OPCODE OPERAND
281301
for line in code.lines() {
282302
let parts: Vec<&str> = line.split_whitespace().collect();
283303
if parts.len() >= 2 {
304+
// First part is opcode, second is operand (unless opcode takes no args)
305+
let opcode = parts[0].to_uppercase();
306+
307+
// Skip if first token is not an opcode (e.g., label)
308+
if !is_il_opcode(&opcode) {
309+
continue;
310+
}
311+
284312
let operand = parts[1];
285-
if operand.chars().next().map(|c| c.is_alphabetic()).unwrap_or(false) {
313+
if is_identifier(operand) && !is_il_opcode(&operand.to_uppercase()) {
286314
analysis.used_variables.insert(operand.to_string());
287315
}
288316
}
289317
}
290318
}
291319

320+
/// Extract references from FBD (Function Block Diagram) bodies.
321+
///
322+
/// Extracts:
323+
/// - Block type names (function/FB calls)
324+
/// - Variable references (inVariable, outVariable, inOutVariable)
325+
/// - Label names for jumps
326+
///
327+
/// FBD is a graphical language where logic is expressed as interconnected blocks.
292328
fn extract_references_from_fbd(fbd: &plcopen::Body_FBD_Inline, analysis: &mut PlcopenAnalysis) {
293329
// Extract from blocks (function blocks, function calls)
294330
for block in &fbd.block {
@@ -353,6 +389,15 @@ fn extract_references_from_fbd(fbd: &plcopen::Body_FBD_Inline, analysis: &mut Pl
353389
}
354390
}
355391

392+
/// Extract references from LD (Ladder Diagram) bodies.
393+
///
394+
/// Extracts:
395+
/// - Contact variable names (input conditions)
396+
/// - Coil variable names (output actions)
397+
/// - Block type names (function/FB calls)
398+
/// - Other variables used in the ladder logic
399+
///
400+
/// LD is a graphical language resembling electrical ladder diagrams.
356401
fn extract_references_from_ld(ld: &plcopen::Body_LD_Inline, analysis: &mut PlcopenAnalysis) {
357402
// LD shares many elements with FBD, plus ladder-specific coils and contacts
358403

@@ -434,6 +479,15 @@ fn extract_references_from_ld(ld: &plcopen::Body_LD_Inline, analysis: &mut Plcop
434479
}
435480
}
436481

482+
/// Extract references from SFC (Sequential Function Chart) bodies.
483+
///
484+
/// Extracts:
485+
/// - Step names (states in the sequence)
486+
/// - Action block qualifiers and references
487+
/// - Transition conditions
488+
/// - Jump step targets
489+
///
490+
/// SFC is a graphical language for sequential control processes.
437491
fn extract_references_from_sfc(sfc: &plcopen::Body_SFC_Inline, analysis: &mut PlcopenAnalysis) {
438492
// SFC shares FBD/LD elements plus SFC-specific steps, transitions, actions
439493

@@ -530,8 +584,56 @@ fn extract_references_from_sfc(sfc: &plcopen::Body_SFC_Inline, analysis: &mut Pl
530584
}
531585
}
532586

587+
/// Remove PLC-style comments from code: `(* ... *)` and `// ...`
588+
///
589+
/// This prevents comment text from being incorrectly identified as
590+
/// variable references or POU calls.
591+
///
592+
/// # Example
593+
/// ```ignore
594+
/// let code = "XIC(Tag1) (* Comment *) OTE(Tag2)";
595+
/// let cleaned = remove_plc_comments(code);
596+
/// // Result: "XIC(Tag1) OTE(Tag2)"
597+
/// ```
598+
fn remove_plc_comments(code: &str) -> String {
599+
let mut result = String::with_capacity(code.len());
600+
let mut chars = code.chars().peekable();
601+
602+
while let Some(ch) = chars.next() {
603+
if ch == '(' && chars.peek() == Some(&'*') {
604+
// Block comment (* ... *)
605+
chars.next(); // consume *
606+
let mut prev = ' ';
607+
while let Some(c) = chars.next() {
608+
if prev == '*' && c == ')' {
609+
break;
610+
}
611+
prev = c;
612+
}
613+
result.push(' '); // Replace comment with space
614+
} else if ch == '/' && chars.peek() == Some(&'/') {
615+
// Line comment // ...
616+
chars.next(); // consume second /
617+
while let Some(c) = chars.next() {
618+
if c == '\n' {
619+
result.push(c);
620+
break;
621+
}
622+
}
623+
} else {
624+
result.push(ch);
625+
}
626+
}
627+
628+
result
629+
}
630+
533631
/// Check if a string is a valid identifier (not a literal or complex expression)
534632
fn is_identifier(s: &str) -> bool {
633+
if s.is_empty() {
634+
return false;
635+
}
636+
535637
// Skip numeric literals
536638
if s.chars().next().map(|c| c.is_ascii_digit()).unwrap_or(false) {
537639
return false;
@@ -547,13 +649,13 @@ fn is_identifier(s: &str) -> bool {
547649
return false;
548650
}
549651

550-
// Must start with letter or underscore and contain only alphanumeric/underscore
652+
// Must start with letter or underscore
551653
let first_char = s.chars().next();
552654
if !matches!(first_char, Some(c) if c.is_alphabetic() || c == '_') {
553655
return false;
554656
}
555657

556-
// Simple identifier check - no dots, brackets, or operators
658+
// Must contain ONLY alphanumeric and underscore - reject anything with punctuation
557659
s.chars().all(|c| c.is_alphanumeric() || c == '_')
558660
}
559661

@@ -578,6 +680,35 @@ fn is_st_keyword(word: &str) -> bool {
578680
)
579681
}
580682

683+
/// Check if a word is an IL (Instruction List) opcode.
684+
///
685+
/// IL opcodes include:
686+
/// - Load/Store: LD, LDN, ST, STN, S, R
687+
/// - Arithmetic: ADD, SUB, MUL, DIV, MOD
688+
/// - Bitwise: AND, OR, XOR, NOT
689+
/// - Comparison: GT, GE, EQ, NE, LE, LT
690+
/// - Flow: JMP, JMPC, CAL, RET
691+
///
692+
/// This prevents opcodes from being flagged as undefined variables.
693+
fn is_il_opcode(word: &str) -> bool {
694+
matches!(word,
695+
// Load/Store
696+
"LD" | "LDN" | "ST" | "STN" | "S" | "R" |
697+
// Stack operations
698+
"PUSH" | "POP" |
699+
// Arithmetic
700+
"ADD" | "SUB" | "MUL" | "DIV" | "MOD" |
701+
// Bitwise
702+
"AND" | "ANDN" | "OR" | "ORN" | "XOR" | "XORN" | "NOT" |
703+
// Comparison
704+
"GT" | "GE" | "EQ" | "NE" | "LE" | "LT" |
705+
// Jump/Call
706+
"JMP" | "JMPC" | "JMPCN" | "CAL" | "CALC" | "CALCN" | "RET" | "RETC" | "RETCN" |
707+
// Other
708+
"NOP"
709+
)
710+
}
711+
581712
fn is_builtin(name: &str) -> bool {
582713
// Common IEC 61131-3 standard functions/function blocks
583714
matches!(name.to_uppercase().as_str(),

‎plceye/src/error.rs‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -47,6 +47,8 @@ impl std::fmt::Display for L5xParseErrorKind {
4747
}
4848
}
4949

50+
impl std::error::Error for L5xParseErrorKind {}
51+
5052
/// Kinds of configuration errors.
5153
#[derive(Debug, Clone, PartialEq, Eq)]
5254
pub enum ConfigErrorKind {
@@ -61,3 +63,5 @@ impl std::fmt::Display for ConfigErrorKind {
6163
}
6264
}
6365
}
66+
67+
impl std::error::Error for ConfigErrorKind {}

‎plceye/src/main.rs‎

Lines changed: 43 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,32 @@ fn show_stats(files: &[PathBuf]) -> ExitCode {
160160
for file in files {
161161
println!("=== {} ===", file.display());
162162

163-
match detector.get_stats_file(file) {
164-
Ok(stats) => {
165-
print_stats(&stats);
163+
// Try to load the project to detect format
164+
match plceye::LoadedProject::from_file(file) {
165+
Ok(project) => {
166+
if project.format == plceye::FileFormat::PlcOpen {
167+
// PLCopen format - show PLCopen stats
168+
match detector.get_plcopen_stats(&project) {
169+
Ok(stats) => {
170+
print_plcopen_stats(&stats);
171+
}
172+
Err(e) => {
173+
eprintln!("Error: {}", e);
174+
has_errors = true;
175+
}
176+
}
177+
} else {
178+
// L5X format - show L5X stats
179+
match detector.get_stats(&project) {
180+
Ok(stats) => {
181+
print_stats(&stats);
182+
}
183+
Err(e) => {
184+
eprintln!("Error: {}", e);
185+
has_errors = true;
186+
}
187+
}
188+
}
166189
}
167190
Err(e) => {
168191
eprintln!("Error: {}", e);
@@ -209,3 +232,20 @@ fn print_stats(stats: &ParseStats) {
209232
println!(" Avg nesting: {:>6.1}", stats.st_avg_nesting);
210233
}
211234
}
235+
236+
fn print_plcopen_stats(stats: &plceye::PlcopenStats) {
237+
println!("POUs (total): {:>6}", stats.pous);
238+
println!(" Functions: {:>6}", stats.functions);
239+
println!(" Function Blocks: {:>6}", stats.function_blocks);
240+
println!(" Programs: {:>6}", stats.programs);
241+
println!(" Empty POUs: {:>6}", stats.empty_pous);
242+
println!();
243+
println!("Language Usage:");
244+
println!(" ST (Structured Text): {:>6}", stats.st_bodies);
245+
println!(" IL (Instruction List): {:>6}", stats.il_bodies);
246+
println!(" FBD (Function Block): {:>6}", stats.fbd_bodies);
247+
println!(" LD (Ladder Diagram): {:>6}", stats.ld_bodies);
248+
println!(" SFC (Sequential Chart): {:>6}", stats.sfc_bodies);
249+
println!();
250+
println!("Variables: {:>6}", stats.variables);
251+
}

‎plcopen/CHANGELOG.md‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,25 @@
11
# Changelog
22

3+
## 0.3.1 (2025-12-14)
4+
5+
### Added
6+
- Full support for graphical language elements (FBD, LD, SFC)
7+
- Text field in `FormattedText` to capture ST/IL code content
8+
- Multiple group reference support in XSD codegen
9+
10+
### Fixed
11+
- Body structures now fully populated with language-specific elements:
12+
- `Body_FBD_Inline`: 13 fields (blocks, variables, labels, jumps)
13+
- `Body_LD_Inline`: 15 fields (contacts, coils, power rails, blocks)
14+
- `Body_SFC_Inline`: 21 fields (steps, transitions, actions)
15+
- Namespace prefix handling in group references
16+
- Recursive type detection for group-expanded elements
17+
18+
### Changed
19+
- XSD parser now collects multiple `<group ref>` elements
20+
- Codegen applies `Box<>` wrapper for recursive types in groups
21+
- Enhanced `xs:any` handling for mixed content extraction
22+
323
## 0.3.0 (2025-12-11)
424
- moved to iec61131 for ST parsing
525

‎plcopen/Cargo.toml‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
[package]
22
name = "plcopen"
3-
version = "0.3.0"
3+
version = "0.3.1"
44
edition = "2021"
55
description = "Parser for PLCopen TC6 XML files (IEC 61131-3 standard exchange format)"
66
license = "MIT"

0 commit comments

Comments
 (0)