plcviz 0.3.3

PLC code visualization - graphs, dependencies, and documentation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
//! PLCopen graph building for plcviz.
//!
//! This module builds various graph types from PLCopen TC6 XML files.

use std::collections::HashSet;
use plcopen::Project;

use crate::graph::{L5xGraph, L5xNodeType};

/// Graph type for PLCopen projects
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum PlcopenGraphType {
    /// Project organization structure (Project → Programs → POUs)
    Structure,
    /// Call graph (function/FB calls)
    CallGraph,
    /// DataType dependencies (struct nesting)
    DataTypeDeps,
}

/// Build graph from PLCopen project
pub struct PlcopenGraphBuilder {
    project: Project,
    graph_type: PlcopenGraphType,
    raw_xml: Option<String>,
}

impl PlcopenGraphBuilder {
    /// Create a new PLCopen graph builder
    pub fn new(project: Project, graph_type: PlcopenGraphType) -> Self {
        Self { 
            project, 
            graph_type,
            raw_xml: None,
        }
    }

    /// Create a builder with raw XML for ST extraction
    pub fn with_xml(project: Project, graph_type: PlcopenGraphType, raw_xml: String) -> Self {
        Self {
            project,
            graph_type,
            raw_xml: Some(raw_xml),
        }
    }

    /// Build the graph
    pub fn build(self) -> L5xGraph {
        match self.graph_type {
            PlcopenGraphType::Structure => self.build_structure_graph(),
            PlcopenGraphType::CallGraph => self.build_call_graph(),
            PlcopenGraphType::DataTypeDeps => self.build_datatype_graph(),
        }
    }

    /// Build structure graph (Project → Programs → Functions/FBs)
    fn build_structure_graph(self) -> L5xGraph {
        let mut graph = L5xGraph::new();

        // Get project name from content header
        let project_name = self.project.content_header
            .as_ref()
            .map(|h| h.name.as_str())
            .unwrap_or("Project");

        // Add root project node
        let project_id = format!("project_{}", project_name);
        graph.add_node(&project_id, project_name, L5xNodeType::Controller);

        // Add POUs
        if let Some(ref types) = self.project.types {
            if let Some(ref pous) = types.pous {
                for pou in &pous.pou {
                    let pou_id = format!("pou_{}", pou.name);
                    let pou_type = &pou.pou_type;
                    
                    let node_type = match pou_type.to_lowercase().as_str() {
                        "program" => L5xNodeType::Program,
                        "function" => L5xNodeType::Routine,
                        "functionblock" => L5xNodeType::Aoi,
                        _ => L5xNodeType::Routine,
                    };

                    let label = format!("{} ({})", pou.name, pou_type);
                    graph.add_node_with_parent(&pou_id, &label, node_type, &project_id);

                    // Connect to project
                    graph.add_edge(&project_id, &pou_id, None);
                }
            }
        }

        graph
    }

    /// Build call graph (POU → POU calls from ST code)
    fn build_call_graph(self) -> L5xGraph {
        let mut graph = L5xGraph::new();

        // First pass: collect all POUs and add as nodes
        let mut pou_names = HashSet::new();
        if let Some(ref types) = self.project.types {
            if let Some(ref pous) = types.pous {
                for pou in &pous.pou {
                    pou_names.insert(pou.name.clone());
                    
                    let pou_id = format!("pou_{}", pou.name);
                    graph.add_node(&pou_id, &pou.name, L5xNodeType::Routine);
                }
            }
        }

        // Second pass: find calls and add edges
        if let Some(ref types) = self.project.types {
            if let Some(ref pous) = types.pous {
                for pou in &pous.pou {
                    let pou_id = format!("pou_{}", pou.name);

                    // Extract calls from bodies
                    // TODO: Implement full extraction once body types are stable
                    let _called_pous: Vec<String> = vec![];
                }
            }
        }

        graph
    }

    /// Build datatype dependency graph
    fn build_datatype_graph(self) -> L5xGraph {
        let mut graph = L5xGraph::new();

        // Get datatypes
        if let Some(ref types) = self.project.types {
            if let Some(ref datatypes) = types.data_types {
                for datatype in &datatypes.data_type {
                    let dt_id = format!("datatype_{}", datatype.name);
                    graph.add_node(&dt_id, &datatype.name, L5xNodeType::Udt);

                    // Extract nested types from struct definitions
                    if let Some(ref base_type) = datatype.base_type {
                        let nested_types = extract_referenced_types(base_type);
                        for nested in nested_types {
                            let nested_id = format!("datatype_{}", nested);
                            // Add edge showing dependency
                            graph.add_edge(&dt_id, &nested_id, Some(&format!("uses {}", nested)));
                        }
                    }
                }
            }
        }

        graph
    }
}

/// Extract called POUs from a POU's body (analyzes all language bodies)
/// TODO: Full implementation pending stable body structure access
#[allow(dead_code)]
fn extract_calls_from_pou_analysis(
    _pou: &plcopen::Root_project_InlineType_types_InlineType_pous_InlineType_pou_Inline,
    _known_pous: &HashSet<String>
) -> Vec<String> {
    // Stub implementation - actual extraction requires better type access
    vec![]
}

/// Extract POU calls from text (ST/IL code)
/// TODO: Complete implementation
#[allow(dead_code)]
fn extract_pou_calls_from_text(code: &str, known_pous: &HashSet<String>) -> Vec<String> {
    let mut calls = Vec::new();
    
    // Simple word-based extraction
    for word in code.split(|c: char| !c.is_alphanumeric() && c != '_') {
        if known_pous.contains(word) {
            calls.push(word.to_string());
        }
    }
    
    calls
}

/// Extract calls from FBD body
/// TODO: Complete implementation

/// Extract referenced type names from a Data (baseType) structure
fn extract_referenced_types(data: &plcopen::Data) -> Vec<String> {
    let mut types = Vec::new();
    
    // Check for struct type
    if let Some(ref struct_type) = data.r#struct {
        // Extract types from struct members
        for var in &struct_type.variable {
            if let Some(ref var_type) = var.r#type {
                // Check if it's a derived (user-defined) type
                if let Some(ref derived) = var_type.derived {
                    types.push(derived.name.clone());
                }
                // Recursively check nested structs
                types.extend(extract_referenced_types(var_type));
            }
        }
    }
    
    // Check for array type
    if let Some(ref array) = data.array {
        if let Some(ref base_type) = array.base_type {
            types.extend(extract_referenced_types(base_type));
        }
    }
    
    // Check for derived (reference to another type)
    if let Some(ref derived) = data.derived {
        types.push(derived.name.clone());
    }
    
    types.sort();
    types.dedup();
    types
}

/// Extract called POUs from a POU's body using raw XML (legacy - kept for reference)
#[allow(dead_code)]
fn extract_calls_from_pou_with_xml(
    pou: &plcopen::Root_project_InlineType_types_InlineType_pous_InlineType_pou_Inline, 
    known_pous: &HashSet<String>,
    raw_xml: &str
) -> Vec<String> {
    let mut calls = Vec::new();

    // Find this POU's XML section
    let pou_name = &pou.name;
    if let Some(pou_start) = raw_xml.find(&format!(r#"<pou name="{}""#, pou_name)) {
        if let Some(pou_end) = raw_xml[pou_start..].find("</pou>") {
            let pou_xml = &raw_xml[pou_start..pou_start + pou_end + 6];
            
            // Extract all ST code from this POU
            let st_blocks = plcopen::st::extract_all_st_from_xml(pou_xml);
            
            for (_, st_code) in st_blocks {
                let pou_calls = extract_calls_from_st(&st_code, known_pous);
                calls.extend(pou_calls);
            }
        }
    }

    calls.sort();
    calls.dedup();
    calls
}

/// Extract function/FB calls from ST code using iec61131 parser
fn extract_calls_from_st(code: &str, known_pous: &HashSet<String>) -> Vec<String> {
    let mut calls = Vec::new();

    // Parse ST code using iec61131
    let mut parser = iec61131::Parser::new(code);
    match parser.parse() {
        Ok(cu) => {
            // Walk the compilation unit to find function/FB calls
            for decl in &cu.declarations {
                extract_calls_from_declaration(decl, known_pous, &mut calls);
            }
        }
        Err(_) => {
            // If parsing fails, fall back to regex
            let re = regex::Regex::new(r"\b([A-Za-z_][A-Za-z0-9_]*)\s*\(").unwrap();
            
            for cap in re.captures_iter(code) {
                if let Some(name) = cap.get(1) {
                    let name_str = name.as_str().to_string();
                    if known_pous.contains(&name_str) {
                        calls.push(name_str);
                    }
                }
            }
        }
    }

    calls
}

/// Extract calls from a declaration (function, program, etc.)
fn extract_calls_from_declaration(decl: &iec61131::PouDeclaration, known_pous: &HashSet<String>, calls: &mut Vec<String>) {
    use iec61131::PouDeclaration;
    
    match decl {
        PouDeclaration::Function(func) => {
            for stmt in &func.body {
                extract_calls_from_statement(stmt, known_pous, calls);
            }
        }
        PouDeclaration::FunctionBlock(fb) => {
            if let Some(ref body) = fb.body {
                for stmt in body {
                    extract_calls_from_statement(stmt, known_pous, calls);
                }
            }
        }
        PouDeclaration::Program(prog) => {
            for stmt in &prog.body {
                extract_calls_from_statement(stmt, known_pous, calls);
            }
        }
        _ => {}
    }
}

/// Recursively extract calls from a statement
fn extract_calls_from_statement(stmt: &iec61131::Statement, known_pous: &HashSet<String>, calls: &mut Vec<String>) {
    use iec61131::Statement;
    
    match stmt {
        Statement::Assignment { value, .. } => {
            extract_calls_from_expression(value, known_pous, calls);
        }
        Statement::If { condition, then_body, elsif_parts, else_body, .. } => {
            extract_calls_from_expression(condition, known_pous, calls);
            for s in then_body {
                extract_calls_from_statement(s, known_pous, calls);
            }
            for (elsif_cond, elsif_body) in elsif_parts {
                extract_calls_from_expression(elsif_cond, known_pous, calls);
                for s in elsif_body {
                    extract_calls_from_statement(s, known_pous, calls);
                }
            }
            if let Some(else_stmts) = else_body {
                for s in else_stmts {
                    extract_calls_from_statement(s, known_pous, calls);
                }
            }
        }
        Statement::While { condition, body, .. } => {
            extract_calls_from_expression(condition, known_pous, calls);
            for s in body {
                extract_calls_from_statement(s, known_pous, calls);
            }
        }
        Statement::Repeat { body, condition, .. } => {
            for s in body {
                extract_calls_from_statement(s, known_pous, calls);
            }
            extract_calls_from_expression(condition, known_pous, calls);
        }
        Statement::For { start, end, step, body, .. } => {
            extract_calls_from_expression(start, known_pous, calls);
            extract_calls_from_expression(end, known_pous, calls);
            if let Some(step_expr) = step {
                extract_calls_from_expression(step_expr, known_pous, calls);
            }
            for s in body {
                extract_calls_from_statement(s, known_pous, calls);
            }
        }
        Statement::Case { selector, cases, else_body, .. } => {
            extract_calls_from_expression(selector, known_pous, calls);
            for case in cases {
                for s in &case.body {
                    extract_calls_from_statement(s, known_pous, calls);
                }
            }
            if let Some(else_stmts) = else_body {
                for s in else_stmts {
                    extract_calls_from_statement(s, known_pous, calls);
                }
            }
        }
        Statement::FunctionCall { name, arguments, .. } => {
            // Check if this is a known POU call
            if known_pous.contains(name) {
                calls.push(name.clone());
            }
            // Also check arguments for nested calls
            for arg in arguments {
                extract_calls_from_argument(arg, known_pous, calls);
            }
        }
        Statement::FbInvocation { instance: _, arguments, .. } => {
            // FB invocations use instance names, not POU names directly
            // But check arguments for nested calls
            for arg in arguments {
                extract_calls_from_argument(arg, known_pous, calls);
            }
        }
        Statement::Return { value, .. } => {
            if let Some(expr) = value {
                extract_calls_from_expression(expr, known_pous, calls);
            }
        }
        _ => {}
    }
}

/// Extract calls from an argument
fn extract_calls_from_argument(arg: &iec61131::Argument, known_pous: &HashSet<String>, calls: &mut Vec<String>) {
    use iec61131::Argument;
    
    match arg {
        Argument::Positional(expr) | Argument::Named { value: expr, .. } => {
            extract_calls_from_expression(expr, known_pous, calls);
        }
        Argument::Output { .. } => {}
    }
}

/// Extract calls from an expression
fn extract_calls_from_expression(expr: &iec61131::Expression, known_pous: &HashSet<String>, calls: &mut Vec<String>) {
    use iec61131::Expression;
    
    match expr {
        Expression::Binary { left, right, .. } => {
            extract_calls_from_expression(left, known_pous, calls);
            extract_calls_from_expression(right, known_pous, calls);
        }
        Expression::Unary { operand, .. } => {
            extract_calls_from_expression(operand, known_pous, calls);
        }
        _ => {}
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_extract_calls_from_st() {
        let code = r#"
            result := MyFunction(x, y);
            IF condition THEN
                AnotherFunction(z);
                SIN(angle);  // standard function, should be ignored
            END_IF;
        "#;

        let mut known_pous = HashSet::new();
        known_pous.insert("MyFunction".to_string());
        known_pous.insert("AnotherFunction".to_string());

        let calls = extract_calls_from_st(code, &known_pous);
        
        assert_eq!(calls.len(), 2);
        assert!(calls.contains(&"MyFunction".to_string()));
        assert!(calls.contains(&"AnotherFunction".to_string()));
        assert!(!calls.contains(&"SIN".to_string()));
    }
}