|
| 1 | +//! The initializer lowering module is responsible for additing initialization logic |
| 2 | +//! to PLC AST nodes. This includes generating default values for variables, handling |
| 3 | +//! constant expressions, and ensuring that all necessary initializations are present |
| 4 | +//! before code generation. The module traverses the AST and modifies nodes as needed |
| 5 | +//! to include initialization code, making sure that the resulting AST is ready for |
| 6 | +//! further compilation stages. |
| 7 | +//! Initialization logic is as follows: |
| 8 | +//! - Every struct(and POU) has an implicit initializer for constant fields. |
| 9 | +//! - The name for this initializer is `<StructName>_init` |
| 10 | +//! - The field is always private to the module |
| 11 | +//! - Every struct(and POU) has a constructor for fields with pointer assignments or non-constant values |
| 12 | +//! - The name for this constructor is `<StructName>_ctor` |
| 13 | +//! - The constructor is always public and implicitly uses the implicit initializer |
| 14 | +//! - Variables of the struct are initialized using the implicit initializer if their value is |
| 15 | +//! derived at compile time, otherwise the constructor is used. |
| 16 | +//! - Global variables are initialized in a global constructor function called `__global_ctor` |
| 17 | +//! - This function is called per module inside the static initialization code |
| 18 | +//! - The function is private to the module |
| 19 | +//! - Stateless POUs (functions and methods) are initialized during their call. |
| 20 | +//! - Variables of a stateless POU of a struct type are initialized using the constructor call. |
| 21 | +//! - External POUs and struct constructors are marked as `extern` and have no body. |
| 22 | +//! - External variables are not re-initialized in the global constructor, they are assumed to be |
| 23 | +//! initialized externally. |
| 24 | +//! - Bulit-in types and variables are not re-initialized in the global |
| 25 | +//! constructor. |
| 26 | +
|
| 27 | +use plc::index::{FxIndexMap, Index}; |
| 28 | +use plc_ast::{ast::AstNode, visitor::AstVisitor}; |
| 29 | + |
| 30 | +pub struct Initializer<'idx> { |
| 31 | + index: &'idx Index, |
| 32 | + implicit_initializers: FxIndexMap<String, AstNode>, |
| 33 | + constructors: FxIndexMap<String, Vec<AstNode>>, |
| 34 | + global_constructor: Vec<AstNode>, |
| 35 | +} |
| 36 | + |
| 37 | +//TODO: might need to be a mutable ast visitor |
| 38 | +impl AstVisitor for Initializer<'_> { |
| 39 | + fn visit_compilation_unit(&mut self, unit: &plc_ast::ast::CompilationUnit) { |
| 40 | + // Read all structs and stateful POU structs, collect their implicit initializers |
| 41 | + // Add a call to the constructor to memcpy the imlicit initializer |
| 42 | + // For each of the call statement or reference in the pou initializer, add an assignment to |
| 43 | + // the constructor |
| 44 | + } |
| 45 | +} |
0 commit comments