PLC programming language security analysis and compilation optimization method and device

CN122547367APending Publication Date: 2026-08-11BEIHANG UNIV
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-07-15
Publication Date
2026-08-11

AI Technical Summary

Technical Problem

当需要修改输出代码的格式、风格或结构时,必须修改生成器的源代码并重新编译,无法在不修改核心代码的情况下定制代码生成行为,存在开发成本高、周期长等缺陷

Benefits of technology

[0016] This invention provides a method and apparatus for secure parsing and compilation optimization of PLC programming languages. The method involves analyzing the PLC programming language to be converted through a lexical/syntax analysis layer and constructing a corresponding syntax tree. A semantic analysis layer performs static security checks on the syntax tree and extracts semantics to construct a structured symbol table system. A code generation layer maps the syntax tree to a core code structure, using a JSON intermediate representation to carry this core structure. The symbol table system is then integrated with the core code structure, compiling to obtain a structured semantic view represented by the JSON intermediate representation data. A template rendering layer maps the JSON intermediate representation data to a defined target code template and performs rendering to generate the corresponding target code string. This solution uses a JSON intermediate representation to decouple the code generation logic from the output format and allows for flexible code output customization through the target code template. While maintaining functional integrity, this solution significantly improves the system's maintainability, scalability, security, and platform adaptability, providing a more flexible and efficient solution for PLC program conversion in industrial automation.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122547367A_ABST
    Figure CN122547367A_ABST
Patent Text Reader

Abstract

The application provides a PLC programming language security analysis and compilation optimization method and device, which analyzes the PLC programming language to be converted and constructs a corresponding syntax tree. The syntax tree is subjected to static security checking, and the syntax tree is subjected to semantic extraction to construct a structured symbol table system. The syntax tree is mapped to a code core structure, the code core structure is carried by a JSON intermediate representation, and the symbol table system and the code core structure are integrated to compile a structured semantic view represented by the JSON intermediate representation data. The JSON intermediate representation data is mapped to a defined target code template based on a template rendering layer and is subjected to rendering to generate a corresponding target code string. The scheme uses the JSON intermediate representation to realize decoupling of code generation logic and output format, realizes flexible code output customization through a target code template, and improves maintainability, expandability and platform adaptation capability of the system.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of compilation technology, and more specifically, to a method and apparatus for safe parsing and compilation optimization of PLC programming languages. Background Technology

[0002] Converting PLC programming languages ​​(such as IEC 61131-3 ST programs) to other programming languages, such as C++, is a challenging yet promising technical practice in the field of industrial automation. It primarily serves scenarios requiring extreme performance, independent software and hardware platforms, and integration with modern IT technologies.

[0003] In existing technologies, open-source compilers are typically used for conversion, such as the MATIEC compiler. MATIEC supports multiple programming languages ​​in the IEC 61131-3 standard, including Structured Text (ST), Instruction List (IL), and Sequential Function Chart (SFC). Its workflow includes lexical analysis, syntax analysis, and semantic analysis of ST programs, and then converts the programs into C language code and binary code.

[0004] However, MATIEC generates target code using direct string concatenation, resulting in a strong coupling between code generation logic and output format. All code templates are hard-coded into the generator's source code. When the format, style, or structure of the output code needs modification, the generator's source code must be modified and recompiled. This makes it impossible to customize code generation behavior without modifying the core code, leading to high development costs and long development cycles. Furthermore, this design makes it difficult to extend the system to support other target languages ​​(such as C++ and Java) and prevents flexible adjustments to code generation strategies based on different application scenarios, limiting the system's applicability and flexibility. Summary of the Invention

[0005] The purpose of this invention is to provide a PLC programming language security parsing and compilation optimization method and apparatus, which uses JSON intermediate representation to decouple code generation logic from output format, and uses target code templates to achieve flexible code output customization, thereby improving the maintainability, scalability and platform adaptability of the system.

[0006] In a first aspect, the present invention provides a method for secure parsing and compilation optimization of PLC programming languages, applied to a PLC programming language secure parsing and compilation optimization system, the system comprising a lexical / syntax analysis layer, a semantic analysis layer, a code generation layer, and a template rendering layer, the method comprising: The lexical / syntax analysis layer analyzes the PLC programming language to be converted and constructs the corresponding syntax tree. Based on the semantic analysis layer, static security verification is performed on the syntax tree, and semantic extraction is performed on the syntax tree to construct a structured symbol table system. The syntax tree is mapped to a core code structure through the code generation layer, the core code structure is carried by JSON intermediate representation, and the symbol table system is integrated with the core code structure to compile a structured semantic view represented by JSON intermediate representation data. Based on the template rendering layer, the JSON intermediate representation data is mapped to the defined target code template and rendered to generate the corresponding target code string.

[0007] In an optional implementation, the step of analyzing the PLC programming language to be converted and constructing the corresponding syntax tree through the lexical / syntax analysis layer includes: In the lexical / syntax analysis layer, a pre-generated lexical analyzer is used to convert the source code character stream of the PLC programming language to be converted into a token sequence according to the defined lexical rules; A pre-generated parser is used to construct a corresponding syntax tree based on the defined syntax rules and the token sequence.

[0008] In an optional implementation, the step of semantic extraction from the syntax tree to construct a structured symbol table system includes: In the semantic analysis layer, the syntax tree is traversed and various semantic entities in the syntax tree are identified; Based on the scope nesting relationship between various semantic entities, a structured symbol table system is constructed. The symbol table system includes multiple symbol tables, each of which has a sub-symbol table list set according to the corresponding scope relationship and is marked with a parent pointer pointing to the parent symbol table.

[0009] In an optional implementation, the symbol table system supports creating a new symbol table as a sub-table of the current symbol table based on the sub-symbol table list when entering a new scope based on the current symbol table during symbol lookup, and restoring to the parent symbol table based on the parent pointer when exiting the scope where the current symbol table is located.

[0010] In an optional implementation, the step of performing static security verification on the syntax tree includes: Traverse the semantic entities in the syntax tree, call the corresponding security verification rules based on the type of the semantic entities, and perform security verification using the security verification rules; Error objects detected by security checks are encapsulated in a structured manner, and relevant context information is output through the logging system.

[0011] In an optional implementation, the step of mapping the syntax tree to a core code structure through the code generation layer, using a JSON intermediate representation to carry the core code structure, and integrating the symbol table system with the core code structure to compile a structured semantic view represented by JSON intermediate representation data includes: In the code generation layer, each syntax element in the syntax tree is traversed, and the corresponding generator class is called for each traversed syntax element; The syntax elements are mapped to the core code structure using the called generator class, and the core code structure is carried in a unified key-value format using JSON intermediate representation. Access the symbol table system to encapsulate and generate context information; The core code structure and context information are integrated, and the integrated result is compiled and represented as a structured semantic view using JSON intermediate representation data.

[0012] In an optional implementation, the step of mapping the JSON intermediate representation data to a defined target code template based on the template rendering layer and performing rendering to generate the corresponding target code string includes: In the template rendering layer, the JSON intermediate representation data is mapped to the defined target code template; The Template Renderer class performs rendering operations on the JSON intermediate representation data mapped to the target code template, wherein the target code template supports reuse operations and modular processing; After rendering is complete, the generated target code string is written to the header file and the source file respectively.

[0013] In an optional implementation, the lexical / syntactic analysis layer, semantic analysis layer, code generation layer, and template rendering layer interact using a unified context access interface.

[0014] In an optional implementation, the system further includes an application entry point, which is responsible for scheduling, resource initialization, and unified management of symbol tables at each layer of the system, and transmits intermediate results and status information between layers through a context structure.

[0015] Secondly, this invention provides a PLC programming language security parsing and compilation optimization device, applied to a PLC programming language security parsing and compilation optimization system, the system comprising a lexical / syntax analysis layer, a semantic analysis layer, a code generation layer, and a template rendering layer, the device comprising: The first construction module is used to analyze the PLC programming language to be converted through the lexical / syntactic analysis layer and construct the corresponding syntax tree; The second construction module is used to perform static security verification on the syntax tree based on the semantic analysis layer, and to extract semantics from the syntax tree to construct a structured symbol table system. The mapping and integration module is used to map the syntax tree into a core code structure through the code generation layer, use JSON intermediate representation to carry the core code structure, and integrate the symbol table system with the core code structure to compile a structured semantic view represented by JSON intermediate representation data. The rendering generation module is used to map the JSON intermediate representation data to the defined target code template based on the template rendering layer and perform rendering to generate the corresponding target code string.

[0016] This invention provides a method and apparatus for secure parsing and compilation optimization of PLC programming languages. The method involves analyzing the PLC programming language to be converted through a lexical / syntax analysis layer and constructing a corresponding syntax tree. A semantic analysis layer performs static security checks on the syntax tree and extracts semantics to construct a structured symbol table system. A code generation layer maps the syntax tree to a core code structure, using a JSON intermediate representation to carry this core structure. The symbol table system is then integrated with the core code structure, compiling to obtain a structured semantic view represented by the JSON intermediate representation data. A template rendering layer maps the JSON intermediate representation data to a defined target code template and performs rendering to generate the corresponding target code string. This solution uses a JSON intermediate representation to decouple the code generation logic from the output format and allows for flexible code output customization through the target code template. While maintaining functional integrity, this solution significantly improves the system's maintainability, scalability, security, and platform adaptability, providing a more flexible and efficient solution for PLC program conversion in industrial automation. Attached Figure Description

[0017] To more clearly illustrate the technical solutions of the embodiments of the present invention, the accompanying drawings used in the embodiments of the present invention will be briefly introduced below. It should be understood that the following drawings only show some embodiments of the present invention and should not be regarded as a limitation on the scope. For those skilled in the art, other related drawings can be obtained based on these drawings without creative effort.

[0018] Figure 1 This is a schematic diagram illustrating the implementation logic of security parsing and compilation optimization based on MATIEC in the existing technology; Figure 2 This is a schematic diagram of the hierarchical structure of the PLC programming language safety parsing and compilation optimization system provided in an embodiment of the present invention; Figure 3 A flowchart illustrating the PLC programming language safety parsing and compilation optimization method provided in this embodiment of the invention; Figure 4 for Figure 3 A flowchart of the sub-steps included in S11; Figure 5 A schematic diagram illustrating the implementation logic of the security parsing and compilation optimization method provided in this embodiment of the invention; Figure 6 for Figure 3 A flowchart of the sub-steps included in S12; Figure 7 for Figure 3 Another flowchart of the sub-steps included in S12; Figure 8 for Figure 3 A flowchart of the sub-steps included in S13; Figure 9 for Figure 3 A flowchart of the sub-steps included in S14; Figure 10 A functional block diagram of the PLC programming language security parsing and compilation optimization device provided in an embodiment of the present invention. Detailed Implementation

[0019] The technical solutions of the present invention will now be described with reference to the accompanying drawings in the embodiments of the present invention.

[0020] Please see Figure 1 This is a schematic diagram of the implementation logic of safety parsing and compilation optimization of PLC programming language based on MATIEC in the existing technology, which specifically includes the following stages: In Phase 1 of lexical analysis, MATIEC uses Flex (a fast lexical analyzer generator) as the lexical analysis tool. It reads the lexical rule file (iec_flex.ll) in `.ll` format, converts the character stream of the IEC61131-3 source code text file into a token sequence according to regular expression rules, and extracts the value corresponding to each token (such as identifier name, constant value, etc.).

[0021] Phase 2 uses Bison (parser generator) as the parsing tool, reads the grammar rule file in `.yy` format (`iec_bison.yy`), and performs reduction and shift operations on the token stream from Phase 1 according to the LALR(1) grammar rules to construct an abstract syntax tree (AST). To solve the problem of identifier type ambiguity in parsing, MATIEC constructs several independent symbol tables, including function_symtable, function_block_type_symtable, program_type_symtable, type_symtable, enumerated_value_symtable, and variable_name_symtable. After parsing is completed, the generated AST identifies all globally declared symbols (including functions, function blocks, programs, types, etc.) and populates the global symbol table.

[0022] Phase 3 is the semantic analysis phase. First, candidate type filling is performed, analyzing the possible data types of each expression and literal and filling the candidate data type fields into the nodes of the AST tree. Next, type narrowing is performed, using contextual information such as operators, function parameters, and assignment statements to deduce the type, narrowing the candidate types down to a single type, determining the actual called function and function block, and filling the corresponding fields in the AST tree. Finally, error reporting is performed, traversing the AST, checking for type incompatibility errors, and outputting detailed error information to the console or log file.

[0023] Phase 4 generates target code through direct string concatenation. By traversing the semantically annotated AST in a single pass, the corresponding C code string is directly concatenated for each AST node. Finally, the concatenated string is written to the output file, generating C source code files (`.c` and `.h` files).

[0024] Existing MATIEC-based technical solutions employ relatively mature tools and implementation methods, compiling ST language into C language in accordance with the IEC 61131-3 standard. However, their technical architecture has high coupling, making modular development and expansion difficult, and their code generation methods are relatively outdated, resulting in poor scalability.

[0025] To address the aforementioned problems in the existing technology, this invention provides a PLC programming language security parsing and compilation optimization method, which offers a more efficient and customizable technical solution in terms of modular design and code generation design.

[0026] Please see Figure 2 This is an application scenario of the PLC programming language security parsing and compilation optimization method provided in the embodiments of the present invention. The application scenario includes a PLC programming language security parsing and compilation optimization system, which includes a lexical / syntax analysis layer, a semantic analysis layer, a code generation layer and a template rendering layer. In addition, the system also includes an application entry point.

[0027] The application entry point is responsible for scheduling, resource initialization, and unified management of symbol tables at each layer of the system, and transmits intermediate results and status information between layers through context structures.

[0028] In this embodiment, the system design emphasizes layered decoupling. Each layer interacts with the other through a JSON data structure and a unified symbol table interface, thereby avoiding strong coupling between modules and making the conversion process maintainable, scalable, and portable to the platform.

[0029] Please see Figure 3 The flowchart below shows a method for secure parsing and compilation optimization of PLC programming languages ​​provided in this embodiment of the invention. This method includes the following steps: S11, the lexical / syntactic analysis layer analyzes the PLC programming language to be converted and constructs the corresponding syntax tree; S12, static security verification is performed on the syntax tree based on the semantic analysis layer, and semantic extraction is performed on the syntax tree to construct a structured symbol table system. S13, the syntax tree is mapped to a core code structure through the code generation layer, the core code structure is carried by JSON intermediate representation, and the symbol table system is integrated with the core code structure to obtain a structured semantic view represented by JSON intermediate representation data; S14, based on the template rendering layer, the JSON intermediate representation data is mapped to the defined target code template and rendered to generate the corresponding target code string.

[0030] In this embodiment, the PLC programming language to be converted can be IEC 61131-3 ST language, and the target code can be C / C++, Java, etc. The following explanation uses C++ as the target code.

[0031] This solution employs a five-layer hierarchical architecture to automate the conversion from IEC 61131-3 ST programs to C / C++ code. The system utilizes ANTLR4 for lexical and syntactic analysis, constructs a structured, hierarchical symbol table system for semantic analysis, uses JSON as an intermediate representation to decouple code generation logic from output format, and leverages a template engine for flexible code output customization. While maintaining functional integrity, this solution significantly improves system maintainability, scalability, and platform adaptability, providing a more flexible and efficient solution for PLC program conversion in industrial automation.

[0032] The specific implementation methods of each of the above steps will be explained in detail below.

[0033] In this embodiment, the syntax processing section uses an ST language lexical and syntax parser built on ANTLR4 to accurately identify the control structures, data types, and module boundaries of the IEC 61131-3 language. For details, please refer to... Figure 4 The steps described above, which analyze the PLC programming language to be converted through lexical / syntactic analysis to construct the corresponding syntax tree, can be implemented in the following ways: S111, in the lexical / syntax analysis layer, a pre-generated lexical analyzer is used to convert the source code character stream of the PLC programming language to be converted into a token sequence according to the defined lexical rules; S112, using a pre-generated parser to construct the corresponding syntax tree according to the defined syntax rules and based on the token sequence.

[0034] Please refer to the following: Figure 5 In this embodiment, the lexical / syntax analysis layer uses ANTLR4 syntax definition files (.g4 format) to define the lexical rules (`IEC61131Lexer.g4`) and syntax rules (`IEC61131Parser.g4`) of IEC 61131-3. The ANTLR4 tool automatically generates the corresponding lexical analyzer and syntax analyzer. The lexical analyzer converts the source code character stream of the PLC programming language to be converted into a token sequence, and the syntax analyzer constructs a parse tree based on the syntax rules and the token sequence.

[0035] In this embodiment, the Visitor pattern of ANTLR4 is used for syntax tree traversal. A custom visitor is implemented by inheriting the `IEC61131ParserBaseVisitor` class, and the `visit*` methods are overridden to handle different types of syntax nodes. The core goal of the parsing phase is not to generate directly usable target code, but to construct a syntax tree that is semantically consistent with the source program and ensure that the syntactic features of the input program can be fully captured. Compared with the traditional Flex / Bison toolchain, ANTLR4 provides more powerful error handling capabilities, can generate parsers with error recovery mechanisms, provide detailed error location and context information when encountering syntax errors, and continue parsing as much as possible to find more errors.

[0036] In the semantic analysis layer, the compiler also performs static security checks. For details, please refer to [link to documentation]. Figure 6 In the PLC programming language security parsing and compilation optimization method provided in this embodiment, the step of performing static security verification on the syntax tree is implemented in the following way: S121, Traverse the semantic entities in the syntax tree, call the corresponding security verification rules based on the type of the semantic entities, and perform security verification using the security verification rules; S122 encapsulates the erroneous objects discovered during security checks in a structured manner and outputs relevant context information through the logging system.

[0037] In this embodiment, semantic security checks are performed synchronously by the symbol table visitor when traversing the AST, and cover the following types of rules: Before registering a new symbol, the system only searches for a symbol with the same name in the current symbol table without tracing back to the parent scope. If the symbol already exists, a duplicate declaration error is reported. In scenarios such as variable references and function calls, the search starts from the current scope and proceeds upwards along the parent pointer chain. If the corresponding declaration is not found after traversing all scopes, an undeclared identifier error is reported. When processing type declarations, function block inheritance declarations, and interface implementation declarations, check whether the referenced type entity has been registered in the current compilation context. If not found, report an illegal type reference error. When processing variable declarations, extract the declaration type and the type of the initialization expression for compatibility verification. Report initialization errors instead of silently passing cases where the types are incompatible. When processing assignment statements, function call parameter bindings, and return value checks, type matching verification is performed one by one, and a type inconsistency error is reported when a mismatch occurs.

[0038] All detected violations are structurally encapsulated through a unified error center. Each error object includes the error category, the name of the involved identifier, the name of the scope, the source file path, and the line and column position in the source code. Detailed contextual information is output through the logging system to facilitate rapid problem localization by developers. After the semantic analysis phase, the system checks the error count. If it is not zero, the compilation process is immediately terminated; the code generation layer and template rendering layer are not executed, and no intermediate representation files or object code files are generated.

[0039] This embodiment ensures that the target code is generated only from source programs that have passed all static verifications through the coverage and forced blocking mechanisms of the aforementioned verification rules. Industrial control systems have strict requirements for the predictability of program behavior. Even if code with semantic defects can pass the C++ compiler, its runtime behavior under the PLC cycle scan execution model may deviate from expectations. Moving the safety boundary forward to the ST compilation stage, rather than relying on downstream compilers or runtime detection as a fallback, is the core design orientation of this embodiment in terms of security and reliability.

[0040] Building upon this, the semantic analysis layer performs further semantic extraction based on the syntax tree. For details, please refer to [link to relevant documentation]. Figure 7 The step of extracting semantics from the syntax tree based on the semantic analysis layer to construct a structured symbol table system can be achieved in the following ways: S123, In the semantic analysis layer, the syntax tree is traversed and various semantic entities in the syntax tree are identified; S124. Based on the scope nesting relationship between various semantic entities, a structured symbol table system is constructed. The symbol table system includes multiple symbol tables. Each symbol table has a sub-symbol table list set according to the corresponding scope relationship and is marked with a parent pointer pointing to the parent symbol table.

[0041] In this embodiment, in the semantic analysis layer, the compiler performs semantic extraction on the syntax tree, including identifying and registering semantic entities such as variables, constants, user-defined types, functions and program blocks, and organizing them into a structured symbol table system (including scope management, type information, visibility rules, etc.).

[0042] Specifically, the system uses the `SymbolParserVisitor` class to traverse the ANTLR4-generated syntax tree in visitor mode, identifying various semantic entities and constructing symbol tables during the traversal. The symbol tables employ a hierarchical structure, implemented using the `SymbolTable` class. Each symbol table contains a parent pointer and a list of child symbol tables, with the parent pointer pointing to the parent symbol table. This creates a tree-like structure to support nested scopes. Based on this constructed symbol table system, symbol lookup uses a recursive upward search mechanism. When a symbol is not found in the current scope, it automatically searches upwards to the parent scope, achieving correct variable scope resolution.

[0043] Specifically, in this embodiment, the symbol table system supports creating a new symbol table as a sub-table of the current symbol table when entering a new scope based on the sub-symbol table list during symbol lookup, and restoring to the parent symbol table based on the parent pointer when exiting the scope where the current symbol table is located.

[0044] In existing technologies, MATIEC uses multiple independent symbol tables to manage different types of symbols. The variable symbol table only supports single-level scope and cannot store information about nested scopes. When a program contains nested scope structures, variable lookups cannot be handled correctly, potentially leading to lookup errors or incorrect scope resolution. Furthermore, MATIEC lacks a unified management mechanism among its six independent symbol tables, with symbol table management logic scattered across different parts of lexical and syntax analysis. Adding new symbol types or modifying symbol table management logic requires modifications in multiple locations, increasing code maintenance complexity. Additionally, the design of multiple independent symbol tables complicates symbol lookup logic, requiring searches in multiple tables and reducing search efficiency.

[0045] In this embodiment, a unified hierarchical symbol table structure is adopted. Each symbol table contains a parent pointer and a list of child symbol tables, forming a tree structure. All types of symbols (variables, functions, function blocks, programs, types, constants, etc.) are stored in the same symbol table structure, and different symbol types are distinguished by the `SymbolKind` enumeration. When entering a new scope, the system creates a new symbol table as a child table of the current symbol table. When exiting a scope, the system restores the parent symbol table. Symbol lookup adopts a recursive upward search mechanism until the symbol is found or the global scope is reached. Therefore, symbol lookup only requires a recursive search within a symbol table tree.

[0046] The hierarchical symbol table structure enables the system to correctly handle complex nested scope scenarios. When a program contains multiple levels of nested scopes, the system maintains an independent symbol table for each level of scope and correctly expresses the nesting relationship of scopes through parent-child relationships. During symbol lookup, the system can correctly find variables according to scope rules, ensuring the correctness of variable lookup. Compared to MATIEC, which can only handle simple single-level scopes, this solution can correctly handle scope nesting of arbitrary depths, avoiding program logic errors caused by scope resolution errors. At the same time, the unified symbol table structure makes symbol table management logic more centralized and clear. When a new symbol type needs to be added, it is only necessary to add the new type to the `SymbolKind` enumeration and add the corresponding processing logic to the symbol table operations, without modifying multiple independent symbol tables. The lookup path is clear and the lookup efficiency is higher.

[0047] More importantly, the hierarchical symbol table structure provides the foundation for the syntactic extensions of the ST language, enabling the system to support object-oriented syntax features such as classes, interfaces, and namespaces. These features require hierarchical scope management to be implemented correctly. MATIEC, lacking hierarchical scope management capabilities, cannot support these syntactic extensions. The hierarchical symbol table design in this solution allows the system to flexibly extend to support these features of modern programming languages, providing a technical foundation for the modernization of the IEC 61131-3 language.

[0048] Building upon this, the syntax tree is mapped to the core structure of the code at the code generation layer. For details, please refer to [link to relevant documentation]. Figure 8 The steps described above—mapping the syntax tree to a core code structure through a code generation layer, using a JSON intermediate representation to carry the core code structure, integrating the symbol table system with the core code structure, and compiling to obtain a structured semantic view represented by the JSON intermediate representation data—can be implemented in the following ways: S131, in the code generation layer, each syntax element in the syntax tree is traversed, and the corresponding generator class is called for the traversed syntax element; S132, the syntax elements are mapped to the core code structure using the called generator class, and the core code structure is carried in a unified key-value format using JSON intermediate representation; S133, access the symbol table system to encapsulate and generate context information; S134, integrate the core code structure and the context information, and use JSON intermediate representation data to compile and represent the integration result as a structured semantic view.

[0049] In this embodiment, at the code generation layer, the system directly maps the syntax tree to the core structure of the code, including global and local variable areas, type definitions, function body organization and control flow, etc.

[0050] To enhance cross-platform capabilities and engineering flexibility, the code generation layer uses a platform-independent JSON intermediate representation to carry the core code structure. Specifically, it uses a unified key-value format to carry the core code structure, describing module division, data layout, execution logic, and lifecycle relationships.

[0051] In its implementation, the system uses the `CodeGenerator` class to traverse the syntax tree using the visitor pattern, calling the corresponding generator class for each syntax element. The code generator employs a separation of responsibilities generator pattern (GeneratorPattern), providing independent generator classes for different types of syntax elements, including `ProgramGenerator`, `FunctionGenerator`, and `FunctionBlockGenerator`. Each generator inherits from the `Generator` base class. Furthermore, it accesses the symbol table system through `GenContext` to obtain unified context information (symbol table, scope, output structure), avoiding the use of global variables. Finally, it integrates the core code structure and the context information obtained from the symbol table system to generate JSON intermediate representation data. This intermediate representation allows ST's semantic features to be accurately presented at a granularity approaching that of the C language engineering system, while avoiding premature binding to specific code styles.

[0052] Based on this, the system integrates the symbol table and syntax tree, abstracts and decouples all generative information, and forms a standardized, stable, and complete structured semantic view.

[0053] In existing technologies, MATIEC directly uses the C++ object tree as the abstract syntax tree without introducing an independent intermediate representation layer. When it is necessary to view or verify the structure of the syntax tree, it can only be done by viewing the C++ objects in memory through a debugger, lacking an intuitive data representation. Developers cannot easily export the syntax tree information for analysis by other tools, nor can they serialize and save the syntax tree information, increasing the difficulty of problem localization and system understanding.

[0054] This solution introduces a JSON intermediate representation to convert the syntax tree into structured data in JSON format. JSON is a human-readable text format that can be directly viewed and edited, and can also be visualized and analyzed using various JSON tools. The system can output the JSON intermediate representation to a file, allowing developers to view and analyze the syntax tree structure using JSON viewers, JSON editors, and other tools. The readability and serializability of the JSON intermediate representation greatly facilitate the debugging and visualization of the syntax tree. When encountering code generation errors, developers can directly view the JSON intermediate representation to quickly locate the problem. JSON visualization tools can display JSON data in tree structures, tables, and other formats, making the complex syntax tree structure intuitive and easy to understand. This convenience not only improves development efficiency but also reduces the learning cost of the system, enabling new developers to understand and master the system more quickly.

[0055] In this embodiment, the lexical / syntactic analysis layer, semantic analysis layer, code generation layer, and template rendering layer interact with each other using a unified context access interface.

[0056] In existing technologies, MATIEC employs a multi-stage compilation architecture, with data passed between compilation stages via global variables, resulting in high coupling between stages. When the implementation of a certain stage needs to be modified, it is often necessary to modify the code of other stages simultaneously, because other stages may depend on the global variables of that stage. This strong coupling makes modular development and unit testing of the system difficult, and also makes code maintenance and extension challenging.

[0057] In this embodiment, a layered architecture is adopted. The semantic analysis layer and the code generation layer interact through a unified context access interface (`GenContext`), avoiding the use of global variables. `GenContext` accesses the application singleton through static methods, providing a unified context access interface for the semantic analysis layer and the code generation layer, including access to the symbol table, scope stack, and code generation structures (`HeaderStructure` and `CFileStructure`), instead of directly accessing global variables.

[0058] Because the semantic analysis layer and the code generation layer interact through a unified interface, the implementation of each layer can be modified independently. As long as the interface remains unchanged, it will not affect other layers. This design enables modular development and unit testing of the system. The semantic analysis and code generation modules can be developed and tested independently. When it is necessary to modify the implementation of a module, only the code of that module needs to be modified, without modifying other modules, thus reducing the complexity of code maintenance. Compared with MATIEC's global variable approach, the modular design of this solution makes it easier to add new features and fix bugs. At the same time, because the responsibilities of each layer are clear, the readability and maintainability of the code are also significantly improved.

[0059] Based on this, the JSON intermediate representation data is mapped to the defined target code template using the template rendering layer, and rendering is performed to generate the corresponding target code string. For details, please refer to [link to relevant documentation]. Figure 9 This step can be achieved in the following way: S141, in the template rendering layer, the JSON intermediate representation data is mapped to the defined target code template; S142, Rendering operation is performed on the JSON intermediate representation data mapped to the target code template through the Template Renderer class, wherein the target code template supports reuse operations and modular processing; S143. After rendering is complete, the generated target code string is written to the header file and the source file respectively.

[0060] In this implementation, during the template rendering stage, the system uses the Inja template engine to map the aforementioned JSON intermediate representation data to user-defined target code templates, such as C code templates and Java code modules, to achieve adaptability to different platforms and different engineering specifications.

[0061] In terms of implementation, the system manages the template rendering process through the `TemplateRenderer` class. Template files use the Jinja2 syntax format (with the `.j2` extension), supporting features such as variable interpolation, conditional statements, loop iteration, and template inclusion. The template system also supports modular design, enabling template reuse and modularization. The Inja engine also supports custom callback functions; the system registers auxiliary functions such as `indent` (indentation function) and `substr` (substring function) for formatting within the template.

[0062] After rendering is complete, the system writes the generated target code string into the `.h` and `.cpp` files respectively, thus achieving the separate generation of header files and source files.

[0063] In this embodiment, not only can the structure, naming conventions, and style of the output files be kept consistent, but the template can also be quickly adapted to the requirements of different controllers or engineering libraries without modifying the generation logic, thus achieving complete decoupling between the code generation logic and the output format.

[0064] In this embodiment, the system's log management and configuration management are implemented using glog, and unit testing uses gtest, ensuring traceability, debuggability, and the ability to reproduce experimental environments in large-scale engineering scenarios. The entire system can run in a C++17 and CMake build environment, guaranteeing high performance and good cross-platform support.

[0065] In this embodiment, compared to the existing method where MATIEC generates code by directly concatenating strings, resulting in strong coupling between the code generation logic and the output format, which necessitates modifying the source code and recompiling to support other target languages, this embodiment uses a template engine (Inja) for code generation, completely separating the code generation logic from the output format.

[0066] The code generator is only responsible for converting the syntax tree into a platform-independent JSON intermediate representation. The code format is defined by a separate template file (`.j2` file). This JSON intermediate representation does not contain any target language-specific information, but only describes the semantic structure of the program. Different target languages ​​only need to provide the corresponding template file, and the template engine can render the same JSON data into code in different languages.

[0067] Because of the decoupling of code generation logic and output format, the system can quickly adapt to different coding style requirements and target languages ​​by replacing template files without modifying the core code. For example, when it is necessary to adapt to different PLC controller platforms or support new target languages, only the corresponding template files need to be prepared, without modifying the code generation logic. In practical applications, this technology can support multiple different code output formats and multiple target languages. In contrast, MATIEC, due to its hard-coding limitations, can only support a fixed code format and a single target language. This flexibility and multi-target language support capability enable this technology to adapt to a wider range of application scenarios, enhancing the system's practical value and market competitiveness.

[0068] In summary, the PLC programming language security parsing and compilation optimization scheme provided in this embodiment, based on the above implementation methods, achieves significant improvements in maintainability, scalability, flexibility, and debugging convenience while maintaining functional integrity. These technical effects enable this scheme to better meet the needs of the industrial automation field for PLC program conversion systems, providing a more flexible, efficient, and reliable solution for industrial automation applications.

[0069] Based on the same inventive concept, please refer to Figure 10 This invention also provides a functional module diagram of a PLC programming language security parsing and compilation optimization device. This embodiment can divide the PLC programming language security parsing and compilation optimization device into functional modules based on the above method embodiments. For example, each function can be divided into its own functional modules, or two or more functions can be integrated into one processing module. The integrated module can be implemented in hardware or as a software functional module. It should be noted that the module division in this embodiment is illustrative and only represents one logical functional division; other division methods may be used in actual implementation.

[0070] For example, when dividing functional modules according to their respective functions, Figure 10 The PLC programming language security parsing and compilation optimization device shown is only a schematic diagram. This device may include a first building module, a second building module, a mapping integration module, and a rendering generation module. The functions of each module of this PLC programming language security parsing and compilation optimization device will be described in detail below.

[0071] The first construction module is used to analyze the PLC programming language to be converted through the lexical / syntactic analysis layer and construct the corresponding syntax tree; The second construction module is used to perform static security verification on the syntax tree based on the semantic analysis layer, and to extract semantics from the syntax tree to construct a structured symbol table system. The mapping and integration module is used to map the syntax tree into a core code structure through the code generation layer, use JSON intermediate representation to carry the core code structure, and integrate the symbol table system with the core code structure to obtain a structured semantic view represented by JSON intermediate representation data; The rendering generation module is used to map the JSON intermediate representation data to the defined target code template based on the template rendering layer and perform rendering to generate the corresponding target code string.

[0072] The PLC programming language security parsing and compilation optimization device provided in this embodiment can be used to execute the PLC programming language security parsing and compilation optimization method under any of the above embodiments. For details not covered in this embodiment, please refer to the corresponding descriptions in the above embodiments. This embodiment will not elaborate further here.

[0073] In the embodiments provided by this invention, it should be understood that the disclosed apparatus and method can be implemented in other ways. The apparatus embodiments described above are merely illustrative. For example, the division of units is only a logical functional division, and in actual implementation, there may be other division methods. Furthermore, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Additionally, the displayed or discussed mutual couplings, direct couplings, or communication connections may be through some communication interfaces; indirect couplings or communication connections between devices or units may be electrical, mechanical, or other forms.

[0074] Furthermore, the units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0075] Furthermore, the functional modules in the various embodiments of the present invention can be integrated together to form an independent part, or each module can exist independently, or two or more modules can be integrated to form an independent part.

[0076] It should be noted that if the functionality is implemented as a software module and sold or used as an independent product, it can be stored in a computer-readable storage medium. Based on this understanding, the technical solution of this invention, or the part that contributes to the prior art, or a part of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0077] In this document, relational terms such as first and second are used only to distinguish one entity or operation from another entity or operation, without necessarily requiring or implying any such actual relationship or order between these entities or operations.

[0078] The above description is merely an embodiment of the present invention and is not intended to limit the scope of protection of the present invention. For those skilled in the art, the present invention can have various modifications and variations. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the scope of protection of the present invention.

Claims

1. A PLC programming language security parsing and compilation optimization method, characterized in that, A PLC programming language safety parsing and compilation optimization system is applied, the system including a lexical / syntax analysis layer, a semantic analysis layer, a code generation layer, and a template rendering layer, the method including: The lexical / syntax analysis layer analyzes the PLC programming language to be converted and constructs the corresponding syntax tree. Based on the semantic analysis layer, static security verification is performed on the syntax tree, and semantic extraction is performed on the syntax tree to construct a structured symbol table system. The syntax tree is mapped to a core code structure through the code generation layer, the core code structure is carried by JSON intermediate representation, and the symbol table system is integrated with the core code structure to compile a structured semantic view represented by JSON intermediate representation data. Based on the template rendering layer, the JSON intermediate representation data is mapped to the defined target code template and rendered to generate the corresponding target code string.

2. The PLC programming language security parsing and compilation optimization method of claim 1, wherein, The step of analyzing the PLC programming language to be converted and constructing the corresponding syntax tree through the lexical / syntax analysis layer includes: In the lexical / syntax analysis layer, a pre-generated lexical analyzer is used to convert the source code character stream of the PLC programming language to be converted into a token sequence according to the defined lexical rules; A pre-generated parser is used to construct a corresponding syntax tree based on the defined syntax rules and the token sequence.

3. The PLC programming language security parsing and compilation optimization method of claim 1, wherein, The step of semantic extraction from the syntax tree to construct a structured symbol table system includes: In the semantic analysis layer, the syntax tree is traversed and various semantic entities in the syntax tree are identified; Based on the scope nesting relationship between various semantic entities, a structured symbol table system is constructed. The symbol table system includes multiple symbol tables, each of which has a sub-symbol table list set according to the corresponding scope relationship and is marked with a parent pointer pointing to the parent symbol table.

4. The PLC programming language safety parsing and compiling optimization method of claim 3, wherein, The symbol table system supports creating a new symbol table as a sub-table of the current symbol table when entering a new scope based on the sub-symbol table list during symbol lookup, and restoring to the parent symbol table based on the parent pointer when exiting the scope where the current symbol table is located.

5. The PLC programming language security parsing and compilation optimization method of claim 3, wherein, The step of performing static security verification on the syntax tree includes: Traverse the semantic entities in the syntax tree, call the corresponding security verification rules based on the type of the semantic entities, and perform security verification using the security verification rules; Error objects detected by security checks are encapsulated in a structured manner, and relevant context information is output through the logging system.

6. The PLC programming language safety parsing and compilation optimization method of claim 1, wherein, The steps of mapping the syntax tree to a core code structure through the code generation layer, using JSON intermediate representation to carry the core code structure, integrating the symbol table system with the core code structure, and compiling to obtain a structured semantic view represented by JSON intermediate representation data include: In the code generation layer, each syntax element in the syntax tree is traversed, and the corresponding generator class is called for each traversed syntax element; The syntax elements are mapped to the core code structure using the called generator class, and the core code structure is carried in a unified key-value format using JSON intermediate representation. Access the symbol table system to encapsulate and generate context information; The core code structure and context information are integrated, and the integrated result is compiled and represented as a structured semantic view using JSON intermediate representation data.

7. The PLC programming language safety parsing and compilation optimization method of claim 1, wherein, The step of mapping the JSON intermediate representation data to the defined target code template based on the template rendering layer and performing rendering to generate the corresponding target code string includes: In the template rendering layer, the JSON intermediate representation data is mapped to the defined target code template; The Template Renderer class performs rendering operations on the JSON intermediate representation data mapped to the target code template, wherein the target code template supports reuse operations and modular processing; After rendering is complete, the generated target code string is written to the header file and the source file respectively.

8. The PLC programming language safety parsing and compilation optimization method of claim 1, wherein, The lexical / syntactic analysis layer, semantic analysis layer, code generation layer, and template rendering layer interact using a unified context access interface.

9. The PLC programming language safety parsing and compiling optimization method of claim 1, wherein, The system also includes an application entry point, which is responsible for scheduling, resource initialization and unified management of symbol tables at each layer of the system, and transmits intermediate results and status information between layers through a context structure.

10. A PLC programming language security parsing and compilation optimization apparatus, characterized by, A system for safe parsing and compilation optimization of PLC programming languages, comprising a lexical / syntax analysis layer, a semantic analysis layer, a code generation layer, and a template rendering layer, wherein the device includes: The first construction module is used to analyze the PLC programming language to be converted through the lexical / syntactic analysis layer and construct the corresponding syntax tree; The second construction module is used to perform static security verification on the syntax tree based on the semantic analysis layer, and to extract semantics from the syntax tree to construct a structured symbol table system. The mapping and integration module is used to map the syntax tree into a core code structure through the code generation layer, use JSON intermediate representation to carry the core code structure, and integrate the symbol table system with the core code structure to compile a structured semantic view represented by JSON intermediate representation data. The rendering generation module is used to map the JSON intermediate representation data to the defined target code template based on the template rendering layer and perform rendering to generate the corresponding target code string.