Method and system for cobol to java program conversion based on syntax tree

CN122411953BActive Publication Date: 2026-08-21SHANDONG CITY COMMERCIAL BANK COOP ALLIANCE CO LTD
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202610837471.0
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2026-06-11
Publication Date
2026-08-21
Estimated Expiration
2046-06-11

AI Technical Summary

Technical Problem

[0005]本发明提供一种基于语法树的COBOL到Java程序转换方法及系统,旨在解决现有跨语言代码转换过程中人工定制内容易丢失、维护效率低的问题

Benefits of technology

本发明通过构建完整的语义映射框架和专项处理机制,实现了COBOL到Java的高保真、高自动化转换,能够准确处理EVALUATE多重条件、PERFORM VARYING循环、复杂数据类型、COPYBOOK引用、同名变量冲突等复杂场景,生成的Java代码可读性强、性能优异,大大降低了遗留系统迁移的成本和风险。多个技术手段协同作用,例如注解式语义映射与专项处理机制的结合使得框架易于扩展,变量路径跟踪与命名冲突解决共同保证了生成代码的编译正确性,循环变量类型优化与表达式类型推断共同提升了运行效率,这些协同效应产生了预料不到的技术效果。

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122411953B_ABST
    Figure CN122411953B_ABST
Patent Text Reader

Abstract

The application discloses a COBOL-to-Java program conversion method and system based on a syntax tree, belongs to the technical field of computer program language conversion, and comprises the following steps: obtaining a COBOL source program file to be converted and configuration rules; performing lexical analysis and syntax analysis to generate an abstract syntax tree; converting COBOL syntax elements into corresponding Java semantic representations according to pre-defined semantic mapping rules; establishing an accurate access chain of a main program and COPYBOOK internal variables through variable path tracking; detecting and solving naming conflicts of COBOL different-level same-name variables based on a scope tree, and renaming variables by adding a parent class name prefix; and generating the converted Java semantic representations into a Java source code file. The application realizes high-fidelity and high-automation COBOL-to-Java conversion, significantly reduces the migration cost of a legacy system, and generates code with strong readability and excellent performance.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This application relates to a COBOL to Java program conversion method and system based on syntax tree, belonging to the field of computer program language conversion technology. Background Technology

[0002] COBOL, a procedural high-level language specifically designed for business data processing, is still widely used in core business systems such as banking and securities. However, with the development of information technology, COBOL systems face problems such as performance bottlenecks, talent shortages, and platform dependence, necessitating a migration to the modern Java language.

[0003] Most existing conversion tools use text replacement or simple syntax analysis, which makes it difficult to handle the complex syntax structures unique to COBOL (such as EVALUATE statements, PERFORM VARYING loops, multi-level data units, 88 conditions, REDEFINES, CMP / COMP-3 data types, etc.), resulting in logical errors, poor readability, and the need for a lot of manual correction in the converted code.

[0004] Furthermore, COBOL and Java differ fundamentally in variable naming rules, data type systems, and memory access methods. Existing solutions lack systematic semantic mapping and conflict resolution mechanisms, making it impossible to achieve high-fidelity automated conversion. Summary of the Invention

[0005] This invention provides a COBOL to Java program conversion method and system based on syntax tree, aiming to solve the problems of easy loss and low maintenance efficiency in the existing cross-language code conversion process due to manual customization.

[0006] The technical solution adopted by this application to solve its technical problem is: On the one hand, a method for converting COBOL to Java programs based on a syntax tree is provided, including: obtaining the COBOL source program file to be converted and configuration rules; performing lexical and syntactic analysis on the COBOL source program file to generate an abstract syntax tree; traversing the abstract syntax tree and converting COBOL syntax elements into corresponding Java semantic representations according to predefined semantic mapping rules, wherein the semantic mapping rules dynamically register semantic converters through an annotation mechanism; handling references to external COPYBOOK files by the COBOL program and establishing a precise access chain between the main program and the internal variables of the COPYBOOK through variable path tracking; detecting and resolving naming conflicts of variables with the same name at different levels in COBOL based on a scope tree and renaming variables by adding a parent class name prefix; and generating Java source code files from the converted Java semantic representations.

[0007] As a preferred approach, during the conversion of COBOL syntax elements into their corresponding Java semantic representations, specific COBOL statements undergo specialized processing: multiple ALSO conditions in the EVALUATE statement are converted into nested if-else structures and condition branch missing alerts are generated; the PERFORM VARYING loop statement is converted into a Java for loop and the loop variable is type-optimized; cross-data type safe conversion is performed on the MOVE and COMPUTE assignment statements, and structure attribute copying is performed on the MOVE CORR statement.

[0008] On the other hand, a COBOL to Java program conversion system based on a syntax tree is provided, including: a source program acquisition module, a syntax parsing module, a semantic conversion engine, an external reference processing module, a variable naming conflict resolution module, and a code generation module, which are used to implement the steps of the above methods respectively.

[0009] One of the above technical solutions has the following advantages or beneficial effects: This invention achieves high-fidelity, highly automated conversion from COBOL to Java by constructing a complete semantic mapping framework and specialized processing mechanisms. It accurately handles complex scenarios such as multiple EVALUATE conditions, PERFORM VARYING loops, complex data types, COPYBOOK references, and name conflicts. The generated Java code is highly readable and performs excellently, significantly reducing the cost and risk of migrating legacy systems. Multiple technical approaches work synergistically; for example, the combination of annotation-based semantic mapping and specialized processing mechanisms makes the framework easily extensible; variable path tracking and naming conflict resolution jointly ensure the compilation correctness of the generated code; and loop variable type optimization and expression type inference jointly improve runtime efficiency. These synergistic effects produce unexpected technical benefits. Attached Figure Description

[0010] Figure 1 This is a flowchart illustrating a syntax tree-based COBOL to Java program conversion method according to an exemplary embodiment; Figure 2 This is a simplified structural diagram of a syntax tree-based COBOL to Java program conversion system according to an exemplary embodiment; Figure 3 This is a schematic diagram of the overall architecture of a syntax tree-based COBOL to Java program conversion system, according to an exemplary embodiment. Figure 4 This is a schematic diagram of a semantic transformation framework in a semantic transformation engine, according to an exemplary embodiment. Detailed Implementation

[0011] To more clearly illustrate the technical features of this application, the following detailed description is provided through specific embodiments and in conjunction with the accompanying drawings.

[0012] Example 1 like Figure 1 As shown in this embodiment, a COBOL to Java program conversion method based on a syntax tree includes the following steps: Step 1: Obtain the COBOL source program file to be converted and the configuration rules.

[0013] Specifically, step 1 includes the following steps: Load the configuration file and read the configuration data in the configuration file, including system parameters, conversion configuration parameters, and conversion rule parameters; The COBOL source program file to be converted is read according to the conversion configuration parameters. The COBOL source program file to be converted includes online program, batch program, subroutine and COPYBOOK file.

[0014] Step 2: Perform lexical and syntactic analysis on the COBOL source program file to generate an abstract syntax tree.

[0015] Specifically, step 2 includes the following steps: Based on COBOL syntax and keyword rules, lexical analysis is performed on the COBOL source program file to generate a lexical unit stream; Syntax analysis is performed based on the lexical unit stream to construct an abstract syntax tree representing the entire COBOL program. The abstract syntax tree contains a hierarchical structure of data part definitions and process part logic. If the COBOL source program file contains COPY or INCLUDE statements, the corresponding COPYBOOK file is recursively read and parsed, and its internal structure is merged into the abstract syntax tree.

[0016] Step 3: Traverse the abstract syntax tree and convert COBOL syntax elements into corresponding Java semantic representations according to predefined semantic mapping rules.

[0017] The semantic mapping rules dynamically register semantic converters through an annotation mechanism. Specifically, a semantic converter class is defined for each COBOL statement type. The semantic converter class inherits from a preset semantic conversion base class (such as CLANGUAGEEntity), and annotations are added to the semantic converter class to identify its mapping relationship. The annotations at least contain the COBOL statement type identifier to be converted. During system initialization, the annotations are scanned through the classpath to instantiate the semantic converter class, and the instance and the corresponding COBOL statement type key-value pair are stored in the semantic mapping cache to establish a mapping relationship between COBOL statement types and semantic converter instances. When traversing the abstract syntax tree, the type of the current syntax tree node is used as the key value to search for and call the corresponding semantic converter instance from the semantic mapping cache to perform the step of converting COBOL syntax elements into corresponding Java semantic representations.

[0018] In the process of converting COBOL syntax elements into their corresponding Java semantic representations, specific COBOL statements undergo special processing, which includes the following steps: The EVALUATE statement's ALSO multiple conditions are converted into nested if-else structures, and a condition branch missing alert is generated. Specifically: the EVALUATE statement is parsed to identify its main expression and multiple WHEN clauses; for WHEN clauses containing the ALSO keyword, the multiple conditions connected by ALSO are combined to form a compound condition expression; according to the logical order of the compound condition expression, a nested if-else structure is generated, where each WHEN clause corresponds to an if or else if branch; after the generated branch structure, it is checked whether a WHEN OTHER clause is included. If not, a condition branch missing alert log is generated. The PERFORM VARYING loop statement is converted into a Java for loop, and the loop variable is optimized in terms of type. Specifically: the PERFORM VARYING statement is parsed to identify the loop variable, initial value, termination condition, and step size; based on the COBOL data type and value range of the loop variable, a matching Java primitive type or custom data type is selected; when the loop variable is an unsigned integer and its maximum possible value does not exceed the Java int type range, it is mapped to the int type; when the value range exceeds int, it is mapped to the long type; for other types such as compressed decimal and signed decimal, it is mapped to predefined custom data types (including BankInteger, BankLong, BankDecimal); based on the loop variable, initial value, termination condition, and step size, a Java for loop structure is generated, including an initialization expression, a conditional expression, and an update expression. This mechanism performs safe cross-data type conversions on MOVE and COMPUTE assignment statements and copies structure attributes for MOVE CORR statements. Specifically: for MOVE statements, it retrieves the data types of the source and target operands; if the data types do not match, it calls a preset type conversion method to convert the source operand to the target operand's type before assignment; for MOVE statements containing the ROUNDED keyword, it calls a rounding function after type conversion before assignment; for MOVE CORR statements, it recursively copies the corresponding sub-element values ​​from the source structure to the corresponding sub-elements in the target structure; for COMPUTE statements, it performs type inference on the result of the expression and performs necessary type conversions before assignment.

[0019] Step 4: Handle the COBOL program's references to external COPYBOOK files, and establish a precise access chain between the main program and the internal variables of COPYBOOK through variable path tracing.

[0020] Specifically, step 4 includes the following steps: During the parsing phase, the location where the COPYBOOK file is referenced is recorded, and an independent Java class representation is generated for each referenced COPYBOOK. For each variable within the COPYBOOK class, construct a path information object. The path information object contains the variable name, its hierarchical path (parent list) in COPYBOOK, storage offset, and length information. In the Java class generated by the main program, the COPYBOOK class is instantiated, and the internal variables of COPYBOOK are accessed through a cascading chain of getter methods based on the path information object, forming the precise access chain.

[0021] Step 5: Based on the scope tree, detect and resolve naming conflicts of variables with the same name at different levels in COBOL, and rename the variables by adding a prefix of the parent class name.

[0022] Specifically, step 5 includes the following steps: Construct a scope tree based on the hierarchical structure of the COBOL program, where each data section level or procedure section constitutes a scope node. Traverse all variable definitions in the scope tree. If a variable with the same name as a parent or ancestor scope is detected in the current scope, the variable name of the parent or ancestor scope is used as a prefix to generate a new variable name. If the new variable name still conflicts with other variable names in the same scope, the variable name from the next higher scope is recursively used as a prefix until the generated variable name is unique.

[0023] Step 6: Generate the converted Java semantic representation into a Java source code file.

[0024] Specifically, step 6 includes the following steps: The converted Java semantic model object is used as input, and the original Java code string is generated through a preset code generation template. The original Java code string is formatted to conform to Java coding standards; Based on the package path configuration of the COBOL source program file, the formatted Java code string is written to the Java source file in the corresponding output directory.

[0025] Example 2 like Figure 2 As shown in this embodiment, a COBOL to Java program conversion system based on a syntax tree includes a source program acquisition module, a syntax parsing module, a semantic conversion engine, an external reference processing module, a variable naming conflict resolution module, and a code generation module.

[0026] The source code acquisition module is used to acquire the COBOL source code files to be converted and the configuration rules. Specifically, this module loads the configuration file, reads the configuration data in the configuration file, including system parameters, conversion configuration parameters, and conversion rule parameters; and reads the COBOL source code files to be converted according to the conversion configuration parameters. The COBOL source code files to be converted include online programs, batch programs, subroutines, and COPYBOOK files.

[0027] The syntax parsing module performs lexical and syntactic analysis on the COBOL source program file, generating an abstract syntax tree (AST). Specifically, based on COBOL syntax and keyword rules, this module uses a lexical analyzer (such as a COBOL lexical analyzer built on ANTLR) to perform lexical analysis on the source program, generating a lexical unit stream. Then, based on the lexical unit stream, it performs syntactic analysis to construct an abstract syntax tree (AST) representing the entire COBOL program. This AST contains a hierarchical structure of data section definitions and procedural logic, including all information such as program structure, data definitions, and procedural parts. If the COBOL source program file contains COPY or INCLUDE statements, the corresponding COPYBOOK file is recursively read and parsed, and its internal structure is merged into the abstract syntax tree.

[0028] The semantic transformation engine traverses the abstract syntax tree (AST) and converts COBOL syntax elements into corresponding Java semantic representations according to predefined semantic mapping rules. The semantic mapping framework uses an annotation mechanism to dynamically register semantic converters: for each COBOL statement type (e.g., IF, MOVE, COMPUTE, EVALUATE), a converter class inheriting from the `CLanguageEntity` base class is defined and annotated with `@SemanticMapping`, which includes an identifier of the COBOL statement type to be converted. At system startup, all annotated classes are scanned through the classpath, instantiated, and registered to the semantic mapping cache (e.g., a `HashMap`) using the COBOL statement type as the key.<String, CLanguageEntity> In the AST (Abstract Syntax Tree), when traversing the AST, the corresponding converter is retrieved from the cache based on the current node type, and its DoTranslate method is called to complete the conversion. This framework supports plug-in extensions; adding new syntax only requires adding a new converter class, without modifying the core code.

[0029] The external reference handling module processes references to external COPYBOOK files by COBOL programs, establishing a precise access chain between the main program and the COPYBOOK's internal variables through variable path tracing. This module parses COPY statements, loads the corresponding COPYBOOK file, records its hierarchical variable structure, and constructs a path information object for each variable. This object contains the variable name, a list of parent variables, storage offset, and length information. When generating Java code, a separate Java class is created for each COPYBOOK, and precise access is achieved in the main program through a getter method chain, such as "COPYBOOKA.getFieldB().getSubField()".

[0030] The variable naming conflict resolution module detects and resolves naming conflicts between variables with the same name at different levels in COBOL based on a scope tree. It renames variables by adding a parent class name prefix. The module handles variable name conflicts at different levels in COBOL using a scope tree built around program segments and data sections. When traversing variable definitions, if a variable with the same name is detected in the current scope, the variable name from the parent scope is used as a prefix (e.g., if the parent variable is "WS-AREA" and the current variable is also "WS-AREA", it is renamed to "wsAreaParent"). If a conflict still exists, higher-level prefixes are recursively added until a unique prefix is ​​found. This algorithm automatically generates variable names that conform to Java naming conventions, avoiding naming conflicts.

[0031] The code generation module is used to generate Java source code files from the converted Java semantic representation. The module uses a template engine (such as Freemarker) to generate Java source code from the converted Java semantic representation (JavaProgram object), formats it (such as Google Java Format), and finally writes it to the output directory.

[0032] Preferably, the system further includes a specialized processing module that performs in-depth optimization for complex syntax in COBOL: (1) EVALUATE statement processing: Parse the conditional expressions in the EVALUATE statement. When the ALSO keyword is encountered, combine multiple conditions into a compound condition to generate a nested if-else structure. For example, the transformation of "EVALUATE A ALSO BWHEN 1 ALSO 2 …" generates the code structure if (A==1&&B==2) { …} else if …. If all WHEN clauses are not matched and no WHEN OTHER is provided, a warning is logged to indicate a possible logical flaw.

[0033] (2) PERFORM VARYING loop processing: Identify the loop variable and its data type (e.g., PIC 9(4) represents a 4-digit unsigned integer), and automatically select the Java type according to the value range: if the loop variable is an unsigned integer and the maximum possible value is ≤2^31-1, it is mapped to int; if it exceeds the int range or is signed, it is mapped to long; for compressed decimal, signed decimal and other types, it is mapped to predefined custom data types (BankInteger, BankLong, BankDecimal). When generating a Java for loop, the loop variable initialization, termination condition and step size update are converted into three expressions of the for statement, and the loop body is embedded in them.

[0034] (3) MOVE / COMPUTE assignment statement processing: Enables safe conversion between data types. For example, in COBOL, when MOVE an alphanumeric field to a numeric field, the type conversion method is automatically called. For MOVE CORR, the fields of the structure are recursively copied. For the ROUNDED keyword, the rounding function is called during assignment.

[0035] Example 3 like Figure 3 As shown, the overall architecture of the COBOL to Java automated translation engine system in this embodiment includes the following main components: 1. COBOL parsing component: The NACA lexical analyzer (e.g., a lexical analyzer based on ANTLR, referred to as the NACA analyzer in this paper): is responsible for converting COBOL source code into a lexical unit stream. NACA parser: Constructs an abstract syntax tree (AST) based on a stream of lexical units. The preprocessing module processes compiler directives and macro definitions in COBOL programs. Syntax Tree Generation Module: Generates standardized COBOL program abstract syntax trees.

[0036] 2. Core Engine Components: Semantic Conversion Module: Based on a semantic mapping framework, this module converts COBOL semantics into Java semantics. Expression processing module: Handles semantic transformation of complex COBOL expressions. Variable management module: Resolves differences in variable naming conventions between COBOL and Java. Code generation module: Generates Java source code based on the conversion results. Loop statement processing module: processes loop statements such as PERFORM VARYING. Assignment statement processing module: processes assignment statements such as MOVE and COMPUTE. Conditional statement processing module: processes conditional statements such as IF and EVALUATE.

[0037] 3. Shared library components: Utility library: Provides general-purpose utility functions and helper methods for the system. Data type library: Custom Java data types to match COBOL data characteristics. Configuration Management Module: Manages system configuration parameters and conversion rules. Semantic mapping cache: Caches semantic mapping relationships to improve lookup efficiency.

[0038] 4. Web portal component: User interface module: Provides a graphical user interface. Task Management Module: Manages and monitors the execution of conversion tasks. Results display module: Displays conversion results and log information.

[0039] 5. Data Flow: COBOL source code → Parsing components → Syntax tree → Core engine → Java code The calling relationships and data transfer between components.

[0040] 6. Detailed Data Flow Description: The data flow of the entire system can be divided into the following stages: Phase 1: Data Input and Preprocessing The user provides the COBOL source file → file reading module → character set decoding → preprocessing module (handling compilation instructions such as COPY and REPLACE). Output: Preprocessed COBOL source code stream; Phase Two: Lexical and Grammatical Analysis Preprocessed COBOL source code → NACA lexical analyzer → TokenStream. Lexical unit stream → NACA parser → Abstract syntax tree (AST) Output: A complete COBOL program abstract syntax tree (CProgram object); Phase Three: Semantic Transformation and Processing CProgram object → Semantic Transformation module → Traversing syntax tree nodes, Each node → corresponding semantic converter (CLanguageEntity subclass) → Java semantic representation (JavaElement object). Expression node → Expression processing module → JavaExpression object, Variable definition node → Variable management module → JavaVariable object (resolve naming conflicts) Conditional Statement Node → Conditional Statement Processing Module → JavaIfElement / JavaEvaluateIfElement Objects Loop statement node → Loop statement processing module → JavaforElement object, Assignment statement node → Assignment statement processing module → JavaMOVE / JavaCOMPUTE object; Phase Four: Code Generation and Optimization JavaElement object collection → Code generation module → Freemarker template engine Template engine processing → Generates raw Java source code strings. Original Java code → Code optimization module → Google Java Format. Output: Formatted Java source code; Phase 5: Output Results Formatted Java source code → File writing module → Java source files organized according to package structure.

[0041] Figure 4 This demonstrates the overall design of the semantic transformation framework within the semantic transformation engine, achieving efficient transformation from a COBOL syntax tree to a Java semantic model. For example... Figure 4 As shown, the specific design of the semantic transformation framework in the semantic transformation engine is as follows.

[0042] 1. The overall framework adopts a three-tier architecture design: Semantic Conversion Layer: The core processing layer, responsible for the semantic conversion logic from COBOL to Java. COBOL Syntax Model Layer: Input layer, representing the COBOL program structure to be converted. Java Semantic Model Layer: Output layer, representing the transformed Java program structure.

[0043] 2. Detailed functional descriptions of each component: 2.1 Semantic Transformation Layer: The semantic transformation layer is the core of the entire framework, containing all the components that implement semantic transformation functionality.

[0044] 2.1.1 Core Semantic Transformer: Semantic converter base class (CLanguageEntity): The semantic converter base class is the core abstract class of the entire framework, defining a unified interface that all concrete semantic converters must implement. This class defines an abstract method, `DoTranslate`, which all concrete converters inheriting from this class need to implement to complete the conversion from COBOL syntax elements to Java semantic elements. The main function of this base class is: Provides a unified conversion interface specification. To achieve polymorphism in converters, Provides a scalable foundation for the framework; Semantic utility class (CSemanticUtils): The semantic utility class serves as the coordination center of the entire semantic transformation framework, undertaking the core scheduling responsibility during the transformation process. Its main functions include: 1. Semantic Transformer Lookup and Invocation: The system searches for matching semantic transformers in the semantic mapping cache and invokes their DoTranslate method to perform the transformation. 2. Transformation process management: Traverse the COBOL syntax tree and recursively process the transformations of elements at each level. 3. Exception Handling: Capture and record exceptions that occur during the conversion process to ensure the stability of the conversion process. 4. Recursive transformation of child elements: Manages the recursive transformation process of child elements, ensuring the integrity of the transformation. 5. Semantic Mapping Cache Management: Maintains a cache for semantic converter instances to improve lookup efficiency; Expression utility class (CExpressionUtils): The expression utility class is specifically designed for converting COBOL expressions to Java expressions, including various complex expression structures such as arithmetic expressions and conditional expressions. Its main functions include: 1. Expression Type Recognition: Identifies different types of COBOL expressions and dispatches them to the appropriate conversion methods. 2. Arithmetic Expression Conversion: Handles conversions between arithmetic operations such as addition, subtraction, multiplication, and division. 3. Conditional Expression Conversion: Handles conversions for conditions such as equal to, not equal to, greater than, and less than. 4. Function call expression conversion: Handles the conversion of COBOL built-in functions. 5. Type inference and conversion: Infer the type of the expression based on the context and perform necessary type conversions; Semantic mapping cache: Semantic mapping caching is a high-performance caching component that automatically registers semantic transformer instances through annotation mechanisms. Its main features include: 1. Automatic Registration: Semantic mappers are automatically discovered and registered using the @SemanticMapping annotation. 2. Efficient Search: A converter search with O(1) time complexity is achieved through a hash table structure. 3. Dynamic refresh: Supports dynamic refresh of cached content at runtime to adapt to system changes.

[0045] 2.1.2 Specific semantic converters: The framework provides a variety of specific semantic converters, each responsible for converting a class of COBOL syntax structures: 1. Conditional Statement Converter (CIfStatement): Converts COBOL IF statements into Java if-else structures. 2. Assignment Statement Converter (CMOVE): Converts COBOL MOVE statements into Java assignment statements, handling type conversions. 3. Computation Statement Converter (CCOMPUTE): Converts COBOL COMPUTE statements into Java computation expressions. 4. Loop Statement Converter (CPERFORM): Converts COBOL PERFORM statements into Java loop structures. 5. Other semantic converters: Converters that handle other specific COBOL syntax structures.

[0046] 2.2 COBOL Syntax Model Layer: The COBOL syntax model is an abstract representation of the COBOL language structure, including: 1. COBOL Program (CProgram): Represents the complete structure of a COBOL program. 2. COBOL Elements (CBaseElement): Represent various syntax elements in a COBOL program. 3. COBOL Expression (CExpressin): Represents the structure of a COBOL expression. 4. COBOL Terminal (CTerminal): Represents the terminal element in an expression.

[0047] 2.3 Java Semantic Model Layer: The Java Semantic Model is an abstract representation of the Java language structure, including: 1. Java Program: Represents the complete structure of a Java program. 2. Java Element: Represents various elements in a Java program. 3. Java Expression: Represents the structure of Java expressions. 4. Java Terminal: Represents the terminal element in an expression. 5. Java Variable Path: Represents the complete path information of a variable.

[0048] 3. Interaction relationships and data flow between components: 3.1 Initialization Phase: 1. When the system starts, CSemanticUtils uses the Spring framework to scan classes annotated with @SemanticMapping. 2. The specific semantic converter instances discovered are registered in the semantic mapping cache. 3. Once the cache is established, the framework is in a ready state, waiting for conversion requests.

[0049] 3.2 Transition Execution Phase: 1. Entry point call: The conversion process is initiated by calling the CSemanticUtils.translateCProgram method externally. 2. Program Initialization: Create a Java program object and initialize the main class information. 3. Syntax Tree Traversal: Recursively traverse each node of the COBOL syntax tree. 4. Converter Lookup: Based on the current COBOL element type, search the semantic map cache for the corresponding semantic converter. 5. Semantic Transformation: The DoTranslate method of the found semantic transformer is called to perform the specific transformation. 6. Expression processing: For expressions involving transformation, the processing is delegated to CExpressionUtils. 7. Terminal element handling: Terminal elements are handled using the CSemanticUtils.translateTerminal method. 8. Child element recursion: If the current element contains child elements, the transformation of the child elements is processed recursively. 9. Result Assembly: Assemble the transformation results into a complete Java semantic model.

[0050] 3.3 Data Flow: The data flow within the entire framework follows this path: COBOL syntax model → semantic transformation layer → Java semantic model. The specific data transfer process is as follows: 1. The COBOL syntax model is passed as input to the semantic utility class. 2. The semantic utility class coordinates the core semantic converter and specific semantic converters to complete the conversion. 3. Expression utility classes handle complex expression transformations. 4. The conversion results are output in the form of a Java semantic model.

[0051] 4. Technical features and innovations: 4.1 Plug-in Architecture Design: The framework adopts a plug-in architecture, making it very simple to add new semantic converters through a unified base class and annotation mechanism. Developers only need to inherit the CLANguageEntity base class and add the @SemanticMapping annotation to implement new semantic conversion functions without modifying the framework's core code.

[0052] 4.2 Dynamic caching mechanism: Through the semantic mapping caching mechanism, the framework can efficiently find and reuse semantic converter instances, avoiding the overhead of repeatedly creating objects and significantly improving conversion performance.

[0053] 4.3 Layered Decoupling Design: The framework adopts a layered design with clearly defined responsibilities and low coupling between layers. The semantic converter focuses on syntax transformation logic, the utility class is responsible for flow control, and the model class provides data structure support. This design improves the maintainability and scalability of the system.

[0054] 4.4 Unified Expression Processing: To address COBOL's complex expression system, the framework provides a dedicated expression utility class for unified processing, which can correctly handle various arithmetic operations, conditional judgments, and function calls, ensuring the accuracy of the conversion results.

[0055] Example 4 Taking a real-world COBOL program conversion test as an example, this embodiment of a syntax tree-based COBOL to Java program conversion method specifically includes the following steps: S1: Load the configuration file to obtain the COBOL source program path, conversion rules, and runtime parameters.

[0056] S2: Read in the COBOL source program, perform lexical and syntactic analysis on the source code, and generate an Abstract Syntax Tree (AST). This AST is rooted at the CProgram object and contains all data and procedural elements.

[0057] S3: Traverse the AST, obtain the semantic converter corresponding to the current node through the semantic mapping framework, execute the DoTranslate method to convert the COBOL statement into a JavaElement object. For expression nodes, call the expression processing unit to perform type inference and generate a JavaExpression object.

[0058] S4: During the conversion process, when an EVALUATE statement is encountered, the conditional statement processing unit is called to generate nested if-else code according to the EVALUATE statement conversion process, and a branch missing alarm is recorded.

[0059] S5: When a PERFORM VARYING statement is encountered, the loop statement processing unit is called to generate for loop code according to the PERFORM VARYING loop statement conversion process, and the type of the loop variable is optimized.

[0060] S6: When a MOVE or COMPUTE statement is encountered, the assignment statement processing unit is invoked to generate safe assignment code based on the source and target data types, and to handle the CORR and ROUNDED keywords.

[0061] S7: When a COPY statement is encountered, the corresponding COPYBOOK file is loaded, its internal variable structure is parsed, a path information object is generated, and an access path is established in the main program through a getter chain.

[0062] S8: During the variable definition phase, the variable naming conflict resolution module is called to generate unique Java variable names based on the scope tree and parent class prefix algorithm.

[0063] S9: Collect all JavaElement objects and construct a complete JavaProgram object.

[0064] S10: Generate Java source code using the Freemarker template engine, and output it after formatting.

[0065] In this embodiment, multiple technical features work together: annotation-based semantic mapping makes the framework easy to extend; specialized processing mechanisms ensure accurate conversion of complex syntax; variable path tracking and naming conflict resolution ensure the correctness of the generated code compilation; and type optimization and expression inference improve code performance. These features are not simply added together, but work synergistically to achieve high-fidelity and highly automated conversion effects, resulting in unexpected technological advancements.

[0066] This embodiment uses actual COBOL program conversion test as an example. The present invention converts 10,000 COBOL source files containing EVALUATE-ALSO, multi-level nested PERFORM, multiple COPYBOOK references and variables with the same name. The average time is 7 minutes. The converted code can be directly compiled and run without manual correction. Compared with existing text replacement tools, the conversion efficiency is significantly improved, and the readability of the generated code is significantly enhanced.

[0067] The aforementioned BankInteger, BankLong, and BankDecimal are predefined custom data types used to accurately simulate COBOL's compressed decimal and signed decimal characteristics. In one embodiment, BankDecimal can be implemented using Java's BigDecimal class and provides methods for mutual conversion with COBOL data formats. Those skilled in the art can also use other equivalent data structures to implement this.

[0068] Finally, it should be noted that the above embodiments are only used to illustrate the technical solutions of this application and not to limit them. Although this application has been described in detail with reference to the above embodiments, those skilled in the art should understand that modifications or equivalent substitutions can still be made to the specific implementation methods of this application. Any modifications or equivalent substitutions that do not depart from the spirit and scope of this application should be covered within the protection scope of the claims of this application.

Claims

1. A COBOL to Java program conversion method based on syntax trees, characterized in that, Includes the following steps: Step 1: Obtain the COBOL source program file to be converted and the configuration rules; Step 2: Perform lexical and syntactic analysis on the COBOL source program file to generate an abstract syntax tree; Step 3: Traverse the abstract syntax tree and convert COBOL syntax elements into corresponding Java semantic representations according to predefined semantic mapping rules. The semantic mapping rules are dynamically registered through annotation mechanisms. Step 4: Handle the COBOL program's references to external COPYBOOK files, and establish a precise access chain between the main program and the internal variables of COPYBOOK through variable path tracing. Step 5: Based on the scope tree, detect and resolve naming conflicts of variables with the same name at different levels in COBOL, and rename the variables by adding a prefix of the parent class name; Step 6: Generate the converted Java semantic representation into a Java source code file; The semantic mapping rules dynamically register semantic converters through an annotation mechanism, including the following steps: Define a semantic converter class for each COBOL statement type. The semantic converter class inherits from a preset semantic conversion base class and is marked with annotations to identify its mapping relationship. The annotations include at least the COBOL statement type identifier to be converted. During system initialization, the annotation is scanned through the classpath to instantiate the semantic converter class, and the instance and the corresponding COBOL statement type key-value pair are stored in the semantic mapping cache to establish a mapping relationship between COBOL statement type and semantic converter instance; When traversing the abstract syntax tree, the corresponding semantic converter instance is searched and called from the semantic mapping cache according to the type of the current syntax tree node as the key value, so as to perform the step of converting COBOL syntax elements into corresponding Java semantic representations; In the process of converting COBOL syntax elements into their corresponding Java semantic representations, COBOL statements undergo special processing: multiple ALSO conditions in EVALUATE statements are converted into nested if-else structures and condition branch missing alerts are generated; PERFORM VARYING loop statements are converted into Java for loops and the loop variables are optimized for type; MOVE and COMPUTE assignment statements undergo cross-data type safe conversion, and structure attribute copying is performed on MOVE CORR statements. Step 4 includes the following steps: During the parsing phase, the location where the COPYBOOK file is referenced is recorded, and an independent Java class representation is generated for each referenced COPYBOOK. For each variable within the COPYBOOK class, construct a path information object. The path information object contains the variable name, its hierarchical path in COPYBOOK, storage offset, and length information. In the Java class generated by the main program, the COPYBOOK class is instantiated, and the internal variables of COPYBOOK are accessed through a cascading chain of getter methods based on the path information object, forming the precise access chain.

2. The COBOL to Java program conversion method based on syntax tree according to claim 1, characterized in that, Step 1 includes the following steps: Load the configuration file and read the configuration data in the configuration file, including system parameters, conversion configuration parameters, and conversion rule parameters; The COBOL source program file to be converted is read according to the conversion configuration parameters. The COBOL source program file to be converted includes online program, batch program, subroutine and COPYBOOK file.

3. The COBOL to Java program conversion method based on syntax tree according to claim 1, characterized in that, Step 2 includes the following steps: Based on COBOL syntax and keyword rules, lexical analysis is performed on the COBOL source program file to generate a lexical unit stream; Syntax analysis is performed based on the lexical unit stream to construct an abstract syntax tree representing the entire COBOL program. The abstract syntax tree contains a hierarchical structure of data part definitions and process part logic. If the COBOL source program file contains COPY or INCLUDE statements, the corresponding COPYBOOK file is recursively read and parsed, and its internal structure is merged into the abstract syntax tree.

4. The COBOL to Java program conversion method based on syntax tree according to claim 1, characterized in that, Step 5 includes the following steps: Construct a scope tree based on the hierarchical structure of the COBOL program, where each data section level or procedure section constitutes a scope node. Traverse all variable definitions in the scope tree. If a variable with the same name as a parent or ancestor scope is detected in the current scope, the variable name of the parent or ancestor scope is used as a prefix to generate a new variable name. If the new variable name still conflicts with other variable names in the same scope, the variable name from the next higher scope is recursively used as a prefix until the generated variable name is unique.

5. The COBOL to Java program conversion method based on syntax tree according to any one of claims 1-4, characterized in that, Step 6 includes the following steps: The converted Java semantic model object is used as input, and the original Java code string is generated through a preset code generation template. The original Java code string is formatted to conform to Java coding standards; Based on the package path configuration of the COBOL source program file, the formatted Java code string is written to the Java source file in the corresponding output directory.

6. A syntax tree-based COBOL to Java program conversion system, used to implement the syntax tree-based COBOL to Java program conversion method as described in any one of claims 1 to 5, characterized in that, include: The source code acquisition module is used to acquire the COBOL source code files to be converted and the configuration rules. The syntax parsing module is used to perform lexical and syntactic analysis on the COBOL source program file and generate an abstract syntax tree; A semantic transformation engine is used to traverse the abstract syntax tree and convert COBOL syntax elements into corresponding Java semantic representations according to predefined semantic mapping rules. The semantic mapping rules are dynamically registered through an annotation mechanism. The external reference handling module is used to handle COBOL programs' references to external COPYBOOK files, and establishes a precise access chain between the main program and the internal variables of the COPYBOOK through variable path tracing. The variable naming conflict resolution module is used to detect and resolve naming conflicts of variables with the same name at different levels in COBOL based on the scope tree, and rename variables by adding a parent class name prefix; The code generation module is used to generate Java source code files from the converted Java semantic representation.

7. The COBOL to Java program conversion system based on syntax tree according to claim 6, characterized in that, It also includes a special processing module, which is used to perform special processing on COBOL statements during the process of converting COBOL syntax elements into corresponding Java semantic representations: converting multiple ALSO conditions in EVALUATE statements into nested if-else structures and generating condition branch missing alarms. Convert the PERFORM VARYING loop statement into a Java for loop and optimize the type of the loop variable; perform cross-data type safe conversion on the MOVE and COMPUTE assignment statements, and perform structure attribute copying on the MOVECORR statement.

Citation Information

Patent Citations

  • Method and system for converting traditional program language into modern program language

    CN107861728A

  • COBOL code conversion method and device

    CN113986252A