C + + code conversion method and system for nuclear energy field
Through syntax parsing, metamodel construction and static checking, efficient C++ code that complies with nuclear safety regulations is generated, solving the real-time issues and safety risks in the conversion from ST language to C++ code, achieving hard real-time performance and cross-platform compatibility of nuclear control systems, and improving development efficiency and safety.
Patent Information
- Application Number
- CN202510804114.X
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2025-06-16
- Publication Date
- 2025-09-26
AI Technical Summary
Existing technologies make it difficult to efficiently and accurately convert ST language into C++ code, resulting in insufficient real-time performance, high security risks, and poor cross-platform portability of PLC software in the nuclear energy field, which cannot meet the needs of nuclear energy control systems.
By adopting the methods of syntax parsing and optimization, metamodel construction, static checking and security verification, and code generation and optimization, and utilizing ANTLR, Eclipse modeling framework and Acceleo template engine, efficient C++ code that complies with nuclear safety regulations is generated, including syntax tree optimization, nuclear safety rule embedding, real-time verification and cross-platform support.
It achieves hard real-time performance guarantee of nuclear energy control systems, improvement of nuclear energy safety and cross-platform compatibility, reduces the upgrade cost of nuclear energy systems, and improves development efficiency and code maintainability.
Smart Images

Figure CN120704685A_ABST
Abstract
Description
Technical Field
[0001] The present invention belongs to the field of nuclear energy technology, and in particular relates to a method and system for C++ code conversion oriented to the nuclear energy field. Background Art
[0002] In the nuclear energy sector, PLCs (Programmable Logic Controllers) and their associated software play a key role in the control systems of nuclear power plants. These systems ensure the safe operation of nuclear power plants through complex logic control and data processing functions. The ST language, defined by the IEC 61131-3v3 standard, is a high-level programming language widely used for writing PLC software due to its structured and modular nature. However, due to the specificity and safety requirements of the nuclear energy sector, PLC software requires rigorous testing and verification. C++, as an efficient and widely used programming language, excels in many embedded and real-time systems. Therefore, converting PLC programs written in ST to C++ code not only enables compilation and optimization using existing C++ compilers and method chains, but also improves the code's portability and cross-platform capabilities, which is of great significance for software development and maintenance in the nuclear energy sector.
[0003] However, current methods for converting ST to C++ code present numerous challenges. For one thing, ST and C++ differ significantly in syntax, semantics, and data types, making direct conversion difficult. Furthermore, the nuclear energy sector places extremely high demands on software security and reliability, and any conversion errors can have serious consequences. Therefore, an efficient and accurate ST-to-C++ conversion method is urgently needed to meet the PLC software needs of the nuclear energy sector.
[0004] To this end, the present invention designs a C++ code conversion method and system for the nuclear energy field, which is suitable for scenarios such as nuclear reactor control and safety monitoring systems that have extremely high requirements for code real-time performance, reliability and security. Summary of the Invention
[0005] The purpose of the present invention is to provide a method and system for C++ code conversion in the nuclear energy field to solve the technical problems of insufficient real-time performance, high security risks and poor cross-platform portability of codes in nuclear energy control systems.
[0006] To achieve the above object, the present invention provides a method for C++ code conversion in the nuclear energy field, comprising the following steps:
[0007] Step 1: Syntax parsing and optimization: Generate an abstract syntax tree (AST) from the ST source program based on the IEC61131-3v3 standard using the ANTLR syntax parser, and optimize redundant nodes in the AST.
[0008] Step 2: Metamodel construction: Use the Eclipse Modeling Framework (EMF) to build a metamodel adapted to nuclear energy control, define EClass (class), EReference (reference) and EAttribute (attribute), and embed nuclear energy safety rules;
[0009] Step 3: Static checking and security verification: Combine the traversal abstract syntax tree (AST) with the constructed metamodel to generate a traversal model instance. Perform semantic analysis on the traversal model instance to detect illegal member access to undeclared variables and the matching degree of function call parameters, and verify the degree to which the code's real-time response cycle meets the hard real-time requirements of the nuclear power control system.
[0010] Step 4: Code generation and optimization: The Acceleo template engine converts the analyzed and tested traversal model instances into efficient C++ code, supporting recursive parsing of nested expressions, control structure generation, exception handling logic insertion, nuclear reactor control, safety testing, and hardware and software collaborative development; the control structure includes loop branches and conditional branches.
[0011] Preferably, the process of step one is as follows:
[0012] S11. Perform lexical analysis on the ST language source program to generate a lexical unit (Token) sequence;
[0013] S12. Perform grammatical analysis on token sequences based on custom ANTLR grammar rules and construct an abstract syntax tree (AST); the custom ANTLR grammar rules support expressions, statements, and custom data types in the IEC61131-3v3 standard;
[0014] S13. Optimize redundant nodes in the abstract syntax tree (AST) to reduce the depth and complexity of the abstract syntax tree (AST).
[0015] Preferably, the process of step 2 is as follows:
[0016] S21. Define EClass (class) to map key nodes in the abstract syntax tree (AST), including POU Declaration (program organization unit declaration), VariableDeclaration (variable declaration), Expression (expression), and Statement (statement); the POU Declaration (program organization unit declaration) class maps the program organization unit declaration node, including input and output parameters and return type;
[0017] Define the POUDeclaration (Program Organization Unit Declaration) class to map the Program Organization Unit Declaration node, including input and output parameters and return types;
[0018] S22. Establish hierarchical relationships between nodes through EReference (reference), including the association between function declarations and statement bodies, the reference between expressions and variables, and the establishment of hierarchical associations between StatementBody (statement blocks) and Expression (expressions), supporting semantic analysis of complex control logic;
[0019] S23. Nuclear safety rules are embedded in EAttribute (attribute), including variable type constraints, operator priority, real-time verification conditions, variable initial value range verification and operator overloading restrictions.
[0020] Preferably, the process of step three is as follows:
[0021] S31. Use traversal model instances to detect undeclared variables, type mismatch expressions, and illegal member accesses; traversal expression nodes are used to verify that operand types comply with nuclear energy data specifications (e.g., radiation only allows floating-point operations);
[0022] S32. Verify the consistency of function call parameters and declared input and output types;
[0023] S33. Based on nuclear safety rules, check the real-time response threshold and fault tolerance mechanism of the code, and automatically add exception handling blocks (such as out-of-bounds detection and redundant sensor verification).
[0024] Preferably, in step 4, in the process of converting the analyzed and detected traversal model instance into efficient C++ code through the Acceleo template engine:
[0025] Acceleo templates include the POUDeclaration template, which generates the program organization unit declaration, parameter list, return type, and configuration file output path in C++ code; the StatementBody template, which generates the corresponding C++ code block based on the Statement; and the Expression template, which supports recursive parsing of complex expressions and variable name mapping.
[0026] S41. Starting from POU Declaration (Program Organization Unit Declaration), call the POU Declaration (Program Organization Unit Declaration) template to parse layer by layer.
[0027] S42, the control structure in StatementBody (statement block) generates C++ loops, conditional branches, and assignment statements from the ST language, and inserts a periodic timer to monitor real-time performance;
[0028] S43. Use the Expression template to recursively parse nested expressions. Recursively parse the left and right operation trees to generate efficient calculation logic that conforms to the target platform. Add nuclear safety comments (such as " / / [SAFETY]Radiation Level Check") to key code segments to facilitate subsequent audits.
[0029] The present invention also provides a system for a C++ code conversion method for the nuclear energy field, including an input interface, a processing unit, an output interface, and a safety compliance module:
[0030] The input interface is used to receive the ST language source program and nuclear safety configuration parameters of the control system;
[0031] The processing unit is configured to execute the method according to any one of claims 1 to 5 to generate optimized C++ code;
[0032] The output interface is used to generate C++ code files, feedback semantic check results, and indicate potential security risks;
[0033] The safety and compliance module is used to dynamically monitor the code generation process to ensure compliance with nuclear industry standards.
[0034] Preferably, the input interface is designed to be nuclear energy-adaptive, supports input of nuclear energy-specific parameters, including real-time response period (e.g., ≤10ms), radiation threshold (e.g., ≤1000μSv / h), fault tolerance level (e.g., number of redundant sensors), parses user-configured nuclear energy safety rules (e.g., IEC 61508 functional safety level requirements), and transmits them to the processing unit;
[0035] Example: Input an ST program for a nuclear reactor cooling system, including the EmergencyShutdown function and temperature control logic; receive the safety parameters: {"max_response_time":"5ms","radiation_threshold":"500μSv / h"};.
[0036] Preferably, the processing unit is a nuclear energy-specific processing logic, including a syntax parsing subunit, a model building subunit, a semantic checking subunit and a code generation subunit;
[0037] The syntax parsing subunit uses ANTLR to parse the ST program, generate an abstract syntax tree (AST), and optimize redundant nodes (such as merging nested expressions) to ensure that the syntax tree adapts to the real-time requirements of the core energy;
[0038] The model construction sub-unit builds a nuclear energy adaptation meta-model based on EMF and embeds two rules: Rule 1 adds real-time attributes to the FOR loop node (such as MaxExecutionTime = 10ms); Rule 2 associates the safety threshold verification logic with the radiation detection function (CheckRadiation);
[0039] The semantic check subunit checks whether the variable type conforms to nuclear energy data specifications (for example, the temperature variable must be a floating point type) and verifies whether the control logic includes fault tolerance mechanisms (for example, redundant sensor verification before emergency shutdown);
[0040] The code generation subunit generates C++ code using the Acceleo template engine. It supports inserting nuclear safety comments (such as / / [SAFETY]Radiation Overload) in key code sections, adding real-time timers to loop structures, triggering alarms when time limits are exceeded, and optimizing code logic.
[0041] Preferably, the output interface performs customized output for nuclear energy, generates multi-platform code, and outputs C++ files suitable for embedded devices (ARM architecture) and industrial servers (x86 architecture). It supports heterogeneous deployment and provides security audit reports, marking potential risks (such as undeclared variables and real-time limit violations) and recommending improvement measures (such as adding redundant check logic).
[0042] Example: Output file: / nuclear_plant / control.cpp (containing hard real-time assertions and fault-tolerance code); Report content: "A loop period of 12ms was detected, exceeding the safety threshold of 10ms. It is recommended to optimize the algorithm or enable parallel computing."
[0043] Preferably, the security compliance module includes a real-time detection unit, a fault-tolerant logic library, and a security audit engine;
[0044] A real-time detection unit inserts hardware timing instructions during the code generation phase to simulate response time under high-load scenarios;
[0045] Fault-tolerant logic, pre-set nuclear energy-specific exception handling templates (such as sensor failure, data out of bounds), and insert target code on demand;
[0046] The security audit engine performs secondary verification on the generated C++ code to ensure that it is consistent with the input security parameters.
[0047] Therefore, the present invention adopts the above-mentioned C++ code conversion method and system for the nuclear energy field, which has the following beneficial effects:
[0048] (1) Hard real-time performance guarantee: Define real-time constraints (e.g., loop period ≤ 10ms) in the EMF metamodel to ensure millisecond-level response to nuclear reactor emergency shutdown instructions; reduce control delays through code optimization strategies (e.g., loop splitting, parallel computing) to meet the hard real-time requirements of nuclear energy systems;
[0049] (2) Significant improvement in nuclear safety: Through the static semantic checking module, undeclared variables, type mismatches, and illegal member accesses are automatically detected, reducing the risk of major accidents such as nuclear leaks; fault-tolerant mechanisms (such as redundant sensor verification and exception handling logic) are embedded in the generated C++ code to comply with the IEC 61508 nuclear safety standard;
[0050] (3) Enhanced cross-platform compatibility: The generated C++ code can run independently of dedicated PLC hardware, supporting the coordinated deployment of embedded devices (ARM architecture) and industrial servers (x86 architecture), reducing the cost of nuclear energy system upgrades;
[0051] (4) Development efficiency optimization: Model-driven design (MDD) simplifies the code iteration process, shortens the development cycle of nuclear energy control systems, and supports rapid prototype verification.
[0052] The technical solution of the present invention is further described in detail below through the accompanying drawings and embodiments. BRIEF DESCRIPTION OF THE DRAWINGS
[0053] Figure 1 This is a flowchart of a method for C++ code conversion for the nuclear energy field according to an embodiment of the present invention;
[0054] Figure 2 A schematic diagram of a process for generating an abstract syntax tree (AST) in an embodiment of the present invention;
[0055] Figure 3 Schematic diagram of the modified syntax rules of Expression specified in the IEC61131-3 v3 standard in an embodiment of the present invention;
[0056] Figure 4 AST diagram corresponding to the modified grammatical rules of Expression specified in the IEC61131-3 v3 standard in an embodiment of the present invention;
[0057] Figure 5 Schematic diagram of the modified syntax rules of the subrange data type in the IEC61131-3 v3 standard in an embodiment of the present invention;
[0058] Figure 6 This is an AST diagram corresponding to the modified syntax rules of the subrange data type in the IEC61131-3 v3 standard in an embodiment of the present invention;
[0059] Figure 7 Schematic diagram of the modified syntax rules of the array data type in the IEC61131-3 v3 standard in an embodiment of the present invention;
[0060] Figure 8 This is an AST diagram corresponding to the modified syntax rules for the array data type in the IEC61131-3 v3 standard in an embodiment of the present invention;
[0061] Figure 9 A schematic diagram of a declaration design in a metamodel according to an embodiment of the present invention;
[0062] Figure 10 A schematic diagram of a VariableDeclaration design in a metamodel according to an embodiment of the present invention;
[0063] Figure 11 Schematic diagram of the initializer design in the metamodel in an embodiment of the present invention;
[0064] Figure 12 A schematic diagram of the expression design in the metamodel in an embodiment of the present invention;
[0065] Figure 13 A schematic diagram of a statement design in a metamodel according to an embodiment of the present invention;
[0066] Figure 14 A schematic diagram of the process of generating a language model in an embodiment of the present invention;
[0067] Figure 15 Schematic diagram of a portion of the Acceleo template corresponding to a POU Declaration (Program Organization Unit Declaration) in an embodiment of the present invention;
[0068] Figure 16 This is a schematic diagram of a portion of the Acceleo template corresponding to the StatementBody (statement block) in an embodiment of the present invention;
[0069] Figure 17 Schematic diagram of some Acceleo templates corresponding to Expression in an embodiment of the present invention;
[0070] Figure 18 The diagram is a schematic diagram of the structure of a system for converting a model and C++ code for the nuclear energy field according to the present invention. DETAILED DESCRIPTION
[0071] The following detailed description of the embodiments of the present invention provided in the accompanying drawings is not intended to limit the scope of the claimed invention, but rather merely represents selected embodiments of the present invention. All other embodiments derived by persons of ordinary skill in the art based on the embodiments of the present invention without inventive effort shall fall within the scope of protection of the present invention.
[0072] According to an embodiment of the present disclosure, a method and system embodiment for C++ code conversion for the nuclear energy field is provided. It should be noted that the steps shown in the flowchart of the accompanying drawings can be executed in a computer system such as a set of computer-executable instructions, and although a logical order is shown in the flowchart, in some cases, the steps shown or described can be executed in an order different from that shown here.
[0073] Starting from the target source file, the first task is to parse the ST language text into an AST. This embodiment uses the ANTLR tool to generate a parser (syntax parser) and a lexer (lexical parser) to parse the ST language text into an abstract syntax tree. ANTLR generates a corresponding parser based on the input grammar file. The grammar file is a text written in an EBNF-like grammar. According to Appendix A of the international standard document IEC 61131-3v3, the formal specification of ST language elements is defined. This formal specification is written in EBNF grammar. However, as pointed out in the previous related research work, this grammar file has many errors and cannot be used directly in ANTLR. Therefore, it is necessary to write an ST grammar file according to the standard formal specification of IEC 61131-3v3 to make the grammar file suitable for ANTLR use, and then use the generated parser to parse the source text. The optimization strategy adopted here is Eclipse Model Framework (EMF). The AST is first optimized to EMF and the two are associated. Then, the advantages of EMF are used to perform semantic analysis on the AST. After optimization, Eclipse Acceleo is used to perform code generation to achieve the goals of this embodiment.
[0074] See also Figure 1 A method for converting C++ code in the nuclear energy field includes the following steps:
[0075] S101. Write the IEC 61131-3v3 standard form specification as a grammar file that conforms to the ANTLR mode, and use ANTLR to generate the required parser to parse the ST source text into an abstract syntax tree AST.
[0076] See also Figure 2 , S101 includes S1011-S1013, the contents are as follows:
[0077] S1011. Write the ST syntax file according to the standard form specification of IEC 61131-3v3.
[0078] S1012. Generate corresponding parsers Lexer (lexical parser) and Parser (syntax parser) using ANTLR according to the prepared grammar file.
[0079] S1013. Use a parser to convert the ST language text into an abstract syntax tree.
[0080] In S1011, when writing a grammar file, it is divided into two parts: LiteralName and RuleName. These two parts are the parts that need to be paid attention to in the AST that is subsequently parsed. LiteralName appears in the form of TerminalNode in the AST. It is a leaf node that is used to specify the specific lexical unit in the ST formal specification. The formal specification of IEC 61131-3v3 is rewritten into the grammar format of ANTLR to write the LiteralName part. RuleName appears in the form of RuleNode in the AST. It is a subtree that is used to represent the specific application of a grammar rule. The writing of this part cannot directly follow the formal specification of IEC 61131-3v3. In addition to the problems caused by some imperfections in the formal specification, it should also be noted that the subsequent metamodel construction process of this article is subject to the constraints of RuleName.
[0081] The structure of ST text can be divided into several parts. Writing rules for each part can make the organization clearer. Like other high-level languages, the program will have an entry point. In ST, "PROGRAM" is generally used as the beginning of the program, followed by variable declaration, type customization, function, statement, expression. These sections constitute a complete Program. In fact, these sections are highly related. Functions are composed of various statements, and statements are composed of expressions and variables. Each expression is also composed of variables or constants, and variables need to be distinguished by type. Therefore, the following hierarchy can be obtained: POU>STATEMENT>EXPRESSION>VARIABLE>TYPE. Therefore, the basic parts of the rules are selected here for detailed description: expression, custom type and variable declaration.
[0082] According to the expressions specified in the IEC 61131-3v3 standard and the formal specifications in the appendix, the expression rules described can be directly written. However, the AST parsed according to this rule is incomplete, has recognition errors, redundant structures, and the expression is too long, which makes it difficult to generate model instances. This affects the accuracy of the AST and the expressiveness of the model. Therefore, in this embodiment, the rules of the expression part are rewritten. Please refer to Figure 3 and Figure 4 , Figure 3 The modified grammar rules for Expression, Figure 4 The AST corresponding to the modified grammar rules of Expression.
[0083] IEC 61131-3v3 proposes several custom data types, namely subrange, enum, array, struct, and string. This embodiment modifies the rules of each custom type. Here are some selected introductions. Please refer to Figure 5-Figure 8 , Figure 5 Modified syntax rules for the subrange data type, Figure 6 The AST corresponding to the modified grammar rules for the subrange data type, Figure 7 Modified syntax rules for array data types, Figure 8 The AST corresponding to the modified grammar rules for the array data type.
[0084] Semantic analysis of the AST involves processes such as type checking, scope analysis, and semantic constraint checking, which require consideration of the statement context. However, since the AST is context-independent, semantic checking typically utilizes techniques such as symbol tables, contextual reasoning, and control and data flow analysis to ensure correctness. However, this can present drawbacks such as difficulty with left recursion, high backtracking overhead, and complex syntax conflict resolution. Therefore, semantic analysis is performed using model instances, which are instances of the metamodel, to represent the AST.
[0085] S102. Build a metamodel. Leverage the metamodel's easy-to-query mechanism to facilitate traversal for subsequent semantic checking, reducing the complexity of the entire front-end work. The metamodel built for the AST is also based on the IEC 61131-3v3 standard. The metamodel provides a unified framework for defining and describing specific models.
[0086] The metamodel is constructed by referring to the structure of the AST. Essentially, it's the grammar file described above, which is also EBNF according to the IEC61131-3v3 standard. In theory, the AST represents the structure of the ST language's source code. Each rule-formed subtree is part of the source code, and each rule node should generate an EMF model instance. Therefore, based on the ST syntax, the metamodel is divided into several packages. Each package structure contains multiple EClasses (classes), and each EClass (class) can find a corresponding node in the AST. The purpose of the package division is to clarify the hierarchy, facilitating better class-based invocation when generating the model. In practice, during metamodel construction, the EClasses in the members are extended through inheritance to more closely match the rules described above. A primary reason for establishing a metamodel is to include contextual relationships not present in the AST. The specific representation of this contextual relationship in the model is defined through the metamodel's EReference (reference). The entire ST language can be considered to be composed of several basic parts. The EPackage here is also processed according to this logic. Literal, type, variable, and POU (Program Organization Unit) are the basic elements, which are included in Expression and Statement. Moreover, Declaration and Initialization are involved. According to the definition of the document IEC 61131-3v3, all Expression and Statement are already defined, so here we can just create EClass one by one according to the specification. Figures 9-13 , Figure 9 It is a declaration design. Figure 10 It is the VariableDeclaration (variable declaration) design, Figure 11 It is the initializer design. Figure 12 It is an expression design. Figure 13 It is a statement design.
[0087] Through steps S101 and S102, the ST language text is parsed into an AST. Furthermore, a metamodel is established based on the grammatical structure of the ST. After completing these two steps, the metamodel is instantiated into a model instance for semantic analysis and static checking. This instantiation process is performed based on the nodes of the AST syntax tree. The overall idea is to traverse the nodes, instantiate a corresponding model instance when accessing each node, and associate the nodes and model instances using a hashmap to facilitate subsequent queries and other operations. This involves two relatively important processes: traversing the abstract syntax tree and instantiation.
[0088] S103. Perform semantic analysis and static checking on the syntax tree to ensure that the code complies with nuclear safety regulations. Perform semantic analysis on the model instance to detect undeclared variables, illegal member accesses, and function call parameter mismatches. Verify that the code's real-time response cycle meets the hard real-time requirements of the nuclear system.
[0089] With the AST and the model instance, the two are associated in step S103. By traversing the AST, the IR abstract representation of the AST is added using the model instance, and semantic analysis is performed based on the model instance to ensure the correctness of the ST source text.
[0090] Static analysis refers to the process of checking the structure, syntax, semantics, dependencies, etc. of the code itself by analyzing the source code before the program is executed. Different from dynamic analysis such as breakpoint debugging, static analysis does not involve actual program execution, but focuses on the characteristics of the code itself; it usually includes syntax analysis, control flow analysis, data flow analysis, etc. Since step S101 uses ANTLR, the syntax analyzer will check the structural correctness of the code according to the syntax rules, so control flow analysis and data flow analysis are mainly performed in this step. Control flow analysis mainly focuses on structures such as code blocks, conditional statements, loops, and the relationship between structures, detecting unreachable code, dead code, etc.; while data flow analysis mainly detects potential errors, such as undeclared or uninitialized variables, dependencies between data, and other code problems.
[0091] In the whole process, the static analysis part will be carried out for the model instance, and the traversal of the abstract syntax tree mentioned in step S102 will also serve as a dependent path for static analysis. The instantiation process in step S102 is the first traversal of the abstract syntax tree, and its main purpose is to generate a model instance (actually, it also contains a small amount of data flow analysis); the main process of static analysis will be completed on the second traversal of the abstract syntax tree, and a method will be written to implement the listener interface. The method here implements exit(), and the specific implementation function is written based on possible semantic errors. Some of the content contained therein can be defined as semantic errors. According to the cause of the error, a program is written to identify such errors. The content of semantic analysis includes null references, expression type mismatch, access to incorrect members, function call errors, and function block usage errors.
[0092] See also Figure 14 , S103 includes S1031-S1033, the contents are as follows
[0093] S1031. Traverse the abstract syntax tree. Traverse the AST from top to bottom and from left to right recursively. When entering a node, the enter() method of the node is first executed, and then the subtree is recursively visited. When exiting a node, the exit() method is executed.
[0094] S1032. Generate the model instance corresponding to the AST node. The generation of the model instance corresponding to the AST node (the instantiation process) is implemented through the factory function of the metamodel. In fact, most calls to the factory function occur in the exit() method. Because the traversal is accessed recursively, the child node must complete the exit() method first. Therefore, the instantiation process of the language model is bottom-up as a whole. This is to facilitate the setting of EReference (reference) in the parent node.
[0095] After instantiation according to the description process of step S1032, the generated model instance will contain POUDeclaration (program organization unit declaration), VariableDeclaration (variable declaration), AssignmentStatement (assignment statement) and ReturnStatement (return statement); there are also EReferences (references) within these sections. You can refer to the metamodel design in step S1032. For example, after multiple EReferences (references) of VariableDeclaration (variable declaration), you can obtain VariableList (variable list) and then obtain Variable (variable). Therefore, when generating code, POUDeclaration (program organization unit declaration) is regarded as the starting point of everything. Take the template corresponding to FunctionDeclaration (function declaration) in POUDeclaration (program organization unit declaration) as an example, set it to have the function of file output, see Figure 15 Line 9 in ; Also from Figure 15 As can be seen in line 7, the EClass (class) required by this template is FunctionDeclaration (function declaration); Figure 15 Lines 10 to 14 are what will be run when this template is loaded; Figure 15 Lines 3 to 5 are declaration statements that introduce other templates. Here, the templates corresponding to VariableDeclatation and Statements are introduced, such as Figure 15 The stmtBodyGen() statement in line 13 is a call to the Statements template. At this time, it will enter another template for subsequent operations, which is actually similar to function calls in other programming languages.
[0096] S1033. Set reference relationships between model instances. By associating reference relationships between model instances, some redundancy in the AST can be removed. Information that cannot be included in the AST can also be stored in the model instance. For example, the AST does not include contextual relationships, but this information can be recorded and stored using the model instance. Furthermore, the advantage of easy querying of EReferences (references) between model instances can greatly facilitate semantic analysis.
[0097] S104. Combine the Acceleo template engine to convert the optimized model into efficient and reliable C++ code. The main task of this step is Model to text (model to text conversion), that is, to output the target code of the model instance in step S103 through Acceleo. Since Acceleo is driven by template files, the main task of this step is also to write template files. In order to convert a model instance into target code, the template corresponding to the model instance must be found before the conversion can be performed. Acceleo provides an abstract class AbstractAcceleoGenerator, which is the driver of the template file and provides some common functions and methods to make it more convenient to create a custom generator; this abstract class is usually inherited and extended to implement specific code generation logic. After inheriting AbstractAcceleoGenerator, you can rewrite its methods, such as generate(), to meet code generation requirements.
[0098] Since Acceleo also utilizes model-driven development, the metamodel defined in step S102 serves as the input element for Acceleo, while the output element is the target text, which in this example is C++ text. Acceleo transforms models using templates. Templates are a set of rules written in a template language that define how each EAttribute (attribute) and EReference (reference) in the model should be converted to text. Therefore, the template language supports common features such as variables, loops, conditional statements, and template calls, as well as advanced features such as string and set operations.
[0099] From the metamodel in step S102 and the process of AST generating model instances, it can be found that in the entire metamodel hierarchy, the association settings between different EClasses are completed through EReferences; each Acceleo template only targets one EClass, so the calls between templates are particularly important; the so-called code generation is to output the module and the elements therein in a fixed form.
[0100] See Figure 16From line 5, we can see that the corresponding EClass is StatementBody, which is an EReference in FunctionDeclaration. Lines 7 and 16 are judgment statements, which will perform different operations depending on the specific type of statement. For specific types, please refer to the complete metamodel definition in the appendix. Here, we focus on the two statements: assignment and return. Figure 16 The corresponding processing methods are given in Figure 16 Line 9 in the code calls the exprGen() template, which is written for the Expression in the EClass class. Figure 17 Like Statement, Expression also has many categories; the BinaryExpression and VariableExpression mentioned in the above examples are Figure 17 As shown in , here we also use recursive method to call, see Figure 17 In line 7, combined with the design of BinaryExpression by the metamodel, the types of FirstExpression and SecondExpression can be any type of Expression; so here we recursively access and judge both of them, and the operator will be output in the form of text. When we access VariableExpression, we will follow Figure 17 In the expression in lines 10 to 14, the expression of the Variable category will output the corresponding variable name text.
[0101] Therefore, the present invention employs the aforementioned C++ code conversion method and system for the nuclear energy sector. Through layered parsing, model-driven design, and semantic constraint verification, this method addresses the issues of poor cross-platform portability and insufficient real-time performance of PLC programs in nuclear energy control systems, while also improving the maintainability and security of the code. The disclosed embodiments can efficiently generate C++ code that complies with nuclear energy industry standards, supporting the collaborative development of software and hardware for key scenarios such as nuclear reactor control and safety monitoring, reducing nuclear energy system upgrade costs and improving operational reliability.
[0102] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of the present invention rather than to limit the same. Although the present invention has been described in detail with reference to the preferred embodiments, those skilled in the art should understand that they can still modify or replace the technical solutions of the present invention with equivalents, and these modifications or equivalent replacements cannot cause the modified technical solutions to deviate from the spirit and scope of the technical solutions of the present invention.
Claims
1. A method for C++ code conversion in the nuclear energy field, characterized in that: The following steps are involved: Step 1: Syntax parsing and optimization: Generate an abstract syntax tree from the ST source program based on the IEC61131-3v3 standard using the ANTLR syntax parser, and optimize redundant nodes in the abstract syntax tree; Step 2: Metamodel construction: Use the Eclipse modeling framework EMF to build a metamodel adapted to nuclear energy control, define EClass, EReference, and EAttribute, and embed nuclear energy safety rules; Step 3: Static inspection and safety verification; The traversal of the abstract syntax tree is combined with the constructed metamodel to generate a traversal model instance. The traversal model instance is semantically analyzed to detect undeclared variables, illegal member accesses, and function call parameter mismatches, and to verify the extent to which the code's real-time response cycle meets the hard real-time requirements of the nuclear power control system. Step 4: Code generation and optimization: The Acceleo template engine converts the analyzed and tested traversal model instances into efficient C++ code, supporting recursive parsing of nested expressions, control structure generation, exception handling logic insertion, nuclear reactor control, safety testing, and hardware and software collaborative development. Control structures include loop branches and conditional branches.
2. The method for C++ code conversion for the nuclear energy field according to claim 1, characterized in that: The process of step one is as follows: S11. Perform lexical analysis on the ST language source program to generate a lexical unit sequence; S12. Perform grammatical analysis on lexical unit sequences based on custom ANTLR grammar rules and construct an abstract syntax tree; the custom ANTLR grammar rules support expressions, statements, and custom data types in the IEC61131-3v3 standard; S13. Optimize redundant nodes in the abstract syntax tree to reduce the depth and complexity of the abstract syntax tree.
3. The method for C++ code conversion for the nuclear energy field according to claim 2, characterized in that: The process of step 2 is as follows: S21. Define EClass to map key nodes in the abstract syntax tree, including POUDeclaration, VariableDeclaration, Expression, and Statement; where the POUDeclaration class maps the program organization unit declaration node, including input and output parameters and return type; S22. Establish hierarchical relationships between nodes through EReference, including the association between function declarations and statement bodies, the reference between expressions and variables, and the hierarchical association between StatementBody and Expression, supporting semantic analysis of complex control logic; Nuclear safety rules are embedded in S23 and EAttribute, including variable type constraints, operator priority, real-time verification conditions, variable initial value range verification, and operator overloading restrictions.
4. The method for C++ code conversion for the nuclear energy field according to claim 3, characterized in that: The process of step three is as follows: S31. Use traversal model instances to detect undeclared variables, type mismatch expressions, and illegal member accesses; traversal expression nodes are used to verify that operand types comply with nuclear energy data specifications; S32. Verify the consistency of function call parameters and declared input and output types; S33. Based on nuclear safety rules, check the real-time response threshold and fault tolerance mechanism of the code and automatically add exception handling blocks.
5. The method for C++ code conversion for the nuclear energy field according to claim 4, characterized in that: In step 4, the Acceleo template engine converts the analyzed and detected traversal model instance into efficient C++ code: Acceleo templates include the POUDeclaration template, which generates program organization unit declarations, parameter lists, return types, and configuration file output paths in C++ code; the StatementBody template, which generates corresponding C++ code blocks based on Statement; and the Expression template, which supports recursive parsing of complex expressions and variable name mapping. The specific conversion process is as follows: S41. Starting from POUDeclaration, call the POUDeclaration template to parse layer by layer. S42, the control structure in StatementBody generates C++ loops, conditional branches, and assignment statements from the ST language, and inserts a periodic timer to monitor real-time performance; S43. Use Expression templates to recursively parse nested expressions, and recursively parse the left and right operation trees to generate efficient calculation logic that conforms to the target platform; add nuclear safety annotations to key code segments.
6. A system for the method of converting C++ code in the nuclear energy field according to any one of claims 1 to 5, characterized in that: Includes input interface, processing unit, output interface and safety compliance module: The input interface is used to receive the ST language source program and nuclear safety configuration parameters of the control system; The processing unit is configured to execute the method according to any one of claims 1 to 5 to generate optimized C++ code; The output interface is used to generate C++ code files and feedback semantic checking results; The security compliance module is used to dynamically monitor the code generation process.
7. The system of a C++ code conversion method for the nuclear energy field according to claim 6, characterized in that: The input interface is designed for nuclear energy adaptation and supports the input of nuclear energy-specific parameters, including real-time response cycle, radiation threshold, and fault tolerance level. It parses the user-configured nuclear energy safety rules and passes them to the processing unit.
8. The system of a C++ code conversion method for the nuclear energy field according to claim 7, characterized in that: The processing unit is a nuclear energy-specific processing logic, including a syntax parsing subunit, a model building subunit, a semantic checking subunit, and a code generation subunit; Syntax parsing subunit, which parses the ST program through ANTLR, generates an abstract syntax tree and optimizes redundant nodes; The model building subunit builds a nuclear energy adaptation metamodel based on EMF and embeds two rules: Rule 1, adds real-time attributes to the FOR loop node; Rule 2 is the safety threshold verification logic associated with the radiation detection function; The semantic checking subunit detects whether the variable type complies with the nuclear energy data specification and verifies whether the control logic contains fault tolerance mechanisms; The code generation subunit generates C++ code through the Acceleo template engine, supports inserting nuclear safety comments in key code sections, adds real-time timers to loop structures, triggers alarms when time limits are exceeded, and optimizes code logic.
9. The system of a C++ code conversion method for the nuclear energy field according to claim 8, characterized in that: The output interface performs customized nuclear energy output, generates multi-platform code, and outputs C++ files suitable for ARM-based embedded devices and x86-based industrial servers. It supports heterogeneous deployment, provides security audit reports, marks potential risks, and recommends improvement measures.
10. The system of a C++ code conversion method for the nuclear energy field according to claim 9, characterized in that: The security compliance module includes a real-time detection unit, a fault-tolerant logic library, and a security audit engine; A real-time detection unit inserts hardware timing instructions during the code generation phase to simulate response time under high-load scenarios; Fault-tolerant logic, pre-set nuclear energy-specific exception handling templates, and insert target code on demand; The security audit engine performs secondary verification on the generated C++ code to ensure that it is consistent with the input security parameters.
Citation Information
Cited By
Hybrid control model secure compilation method and system based on multi-view intermediate representation
CN122526578A