Code conversion method and device, computer equipment and storage medium

By analyzing and analyzing the abstract syntax tree of the source code, extracting semantic information, and coding and optimizing according to the syntax rules of the target language, the problem of insufficient flexibility and scalability of code conversion tools in the existing technology is solved, and efficient and accurate code conversion and optimization effects are achieved.

CN119621074APending Publication Date: 2025-03-14SHENZHEN LANYOU TECHNOLOGY CO LTD

Patent Information

Application Number
CN202411692096.2
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2024-11-25
Publication Date
2025-03-14

AI Technical Summary

Technical Problem

Existing code conversion tools lack flexibility and scalability, struggle to handle complex language features and meet custom requirements, and fail to make full use of artificial intelligence technology to optimize conversion processes and results.

Method used

By obtaining the source code and the target language, analyzing and generating an abstract syntax tree, analyzing and extracting semantic information, converting it according to the semantic information and the grammatical rules of the target language, and further optimizing the initial conversion code to generate the final translation code.

Benefits of technology

It improves the efficiency and accuracy of code conversion, reduces the workload of manual conversion, ensures that the converted code is not only correct, but also efficient and readable, promotes cross-language programming and code reuse, and reduces software development costs.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN119621074A_ABST
    Figure CN119621074A_ABST
Patent Text Reader

Abstract

The invention belongs to the field of artificial intelligence, and relates to a code conversion method and device, computer equipment and a storage medium, and the method comprises the steps: obtaining a source code and a target language; analyzing the source code to generate an abstract syntax tree; analyzing the abstract syntax tree, and extracting semantic information; according to the semantic information and a grammar rule of a target language, converting the code into the target language to obtain a preliminary conversion code; and further optimizing the preliminarily converted code to generate a final translated code. The automation degree is high, and the workload of manual conversion is greatly reduced; the conversion process is standard and unified, and the consistency and accuracy of code conversion are improved; by analyzing the AST, the source code can be understood more deeply, so that the translation code with higher quality is generated; extension and maintenance are easy, and support for new languages or characteristics can be added according to needs; the optimization step ensures that the converted code is not only correct, but also efficient and high in readability; and cross-language programming and code reuse are promoted.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of artificial intelligence technology, and in particular to a code conversion method, device, computer equipment and storage medium. Background Art

[0002] With the rapid development of technology, the migration and update of software systems has become a common demand. However, manually converting large code bases from one programming language to another is a time-consuming and error-prone task. Existing code conversion tools often lack flexibility and scalability, and have difficulty handling complex language features and meeting customized requirements. In addition, these tools usually cannot fully utilize the latest artificial intelligence technology to optimize the conversion process and results. Therefore, an intelligent and customizable code translation system is needed to improve conversion efficiency and accuracy. Summary of the invention

[0003] In order to solve the above technical problems, on the one hand, the present invention provides a code conversion method, which adopts the following technical solution, including:

[0004] Get source code and target language;

[0005] Parsing the source code to generate an abstract syntax tree;

[0006] Analyze the abstract syntax tree to extract semantic information;

[0007] According to the semantic information and the grammatical rules of the target language, the code is converted into the target language to obtain a preliminary conversion code;

[0008] The preliminary conversion code is further optimized to generate a final translation code.

[0009] Preferably, the step of obtaining source code and target language specifically includes:

[0010] Obtain the source code from a code repository;

[0011] Acquire the target language from an input interface;

[0012] The source code and the target language are stored.

[0013] Preferably, the step of parsing the source code and generating an abstract syntax tree specifically includes:

[0014] Performing lexical analysis on the source code, dividing the character sequence of the source code into lexical units, and assigning a corresponding label to each lexical unit;

[0015] Based on the lexical analysis, the syntax analyzer is used to identify the grammatical structure and construct an abstract syntax tree.

[0016] Preferably, the step of analyzing the abstract syntax tree and extracting semantic information specifically includes:

[0017] Perform static checking on the abstract syntax tree to verify the semantic correctness of the code;

[0018] Optimize the abstract syntax tree to improve the execution efficiency of the program;

[0019] Each node of the abstract syntax tree is traversed, and the syntax structure is processed to extract the semantic information.

[0020] Preferably, the step of converting the code into the target language according to the semantic information and the grammatical rules of the target language to obtain the preliminary converted code specifically comprises:

[0021] Selecting a conversion template according to the grammatical rules of the target language and the semantic information;

[0022] The semantic information is filled into the conversion template to generate source code of the target language to obtain a preliminary conversion code.

[0023] Preferably, the step of further optimizing the preliminary conversion code to generate the final translation code specifically includes:

[0024] Passing the preliminary transformation code to the GPT-4 model;

[0025] The GPT-4 model analyzes the preliminary conversion code and generates optimization suggestions;

[0026] Apply the optimization suggestion to the preliminary conversion code to generate a final translation code.

[0027] Preferably, after the step of further optimizing the preliminary conversion code to generate the final translation code, the method further includes:

[0028] In the target language environment, the translated code is executed to obtain a translated code execution result.

[0029] In order to solve the above technical problems, the present invention further provides a code conversion device, which adopts the following technical solution, including:

[0030] Acquisition module, used to obtain source code and target language;

[0031] A parsing module, used for parsing the source code and generating an abstract syntax tree;

[0032] An extraction module, used for analyzing the abstract syntax tree and extracting semantic information;

[0033] A conversion module, used to convert the code into a target language according to the semantic information and grammar conversion rules to obtain a preliminary conversion code;

[0034] The optimization module is used to further optimize the preliminary conversion code to generate a final translation code.

[0035] In order to solve the above technical problems, the present invention also provides a computer device, which adopts the technical solution described below, including a memory and a processor, wherein the memory stores computer-readable instructions, and the processor implements the steps of the above code conversion method when executing the computer-readable instructions.

[0036] In order to solve the above technical problems, the present invention also provides a computer-readable storage medium, which adopts the technical solution described below, and stores computer-readable instructions on the computer-readable storage medium, which implement the steps of the above-mentioned code conversion method when executed by the processor.

[0037] Compared with the prior art, the present invention mainly has the following beneficial effects: by first obtaining the source code and the target language, and then parsing the source code to generate an abstract syntax tree; then analyzing the abstract syntax tree to extract semantic information; then converting the code to the target language according to the semantic information and the grammatical rules of the target language to obtain a preliminary conversion code; then further optimizing the preliminary conversion code to generate a final translation code; the degree of automation is high, which greatly reduces the workload of manual conversion; the conversion process is standardized and unified, which improves the consistency and accuracy of code conversion; by parsing and analyzing AST, the source code can be understood more deeply, thereby generating higher quality translation code; it is easy to expand and maintain, and support for new languages ​​or features can be added as needed; the optimization step ensures that the converted code is not only correct, but also efficient and readable; it promotes cross-language programming and code reuse, and reduces software development costs; it provides strong tool support for cross-language migration and upgrading of software systems, greatly reduces development costs, and improves the efficiency of software maintenance and evolution. BRIEF DESCRIPTION OF THE DRAWINGS

[0038] In order to more clearly illustrate the scheme in the present invention, a brief introduction is given below to the drawings required for use in the description of the embodiments of the present invention. Obviously, the drawings described below are some embodiments of the present invention. For ordinary technicians in this field, other drawings can be obtained based on these drawings without paying any creative work.

[0039] Figure 1 is an exemplary system architecture diagram in which the present invention can be applied;

[0040] Figure 2is a flow chart of an embodiment of a code conversion method of the present invention;

[0041] Figure 3 It is a schematic structural diagram of an embodiment of a code conversion device of the present invention;

[0042] Figure 4 is a timing diagram of the constituent modules of another code conversion device of the present invention;

[0043] Figure 5 It is a schematic structural diagram of an embodiment of a computer device of the present invention. DETAILED DESCRIPTION

[0044] Unless otherwise defined, all technical and scientific terms used herein have the same meaning as those commonly understood by technicians in the technical field of the present invention; the terms used in the specification of the application herein are only for the purpose of describing specific embodiments and are not intended to limit the present invention; the terms "including" and "having" and any variations thereof in the specification and claims of the present invention and the above-mentioned drawings are intended to cover non-exclusive inclusions. The terms "first", "second", etc. in the specification and claims of the present invention or the above-mentioned drawings are used to distinguish different objects, not to describe a specific order.

[0045] Reference to "embodiments" herein means that a particular feature, structure, or characteristic described in conjunction with the embodiments may be included in at least one embodiment of the present invention. The appearance of the phrase in various places in the specification does not necessarily refer to the same embodiment, nor is it an independent or alternative embodiment that is mutually exclusive with other embodiments. It is explicitly and implicitly understood by those skilled in the art that the embodiments described herein may be combined with other embodiments.

[0046] In order to enable those skilled in the art to better understand the solutions of the present invention, the technical solutions in the embodiments of the present invention will be clearly and completely described below in conjunction with the accompanying drawings.

[0047] like Figure 1 As shown in the figure, the system architecture includes user layer, Langchain integration layer, code processing and analysis layer, core translation function layer, code generation and verification layer, etc.

[0048] The user layer involves user interface / API, translation workflow orchestration, code conversion engine, etc.

[0049] The code processing and analysis layer involves professional code parsing tools and Langchain code loader. Professional code parsing tools are used for abstract syntax tree (AST) generation and semantic analysis. Langchain code loader includes source code loader and code snippet splitter.

[0050] The core translation function layer includes language feature mapping chain, syntax conversion engine, code refactoring engine, identifier renaming tool and code optimization chain.

[0051] The code generation and verification layer includes the target language code generator, syntax checker, unit test generation chain, code formatting tool, knowledge base and storage, and infrastructure layer. The knowledge base and storage include language feature mapping database, conversion pattern library, and code example library. The infrastructure layer includes large-scale language model (LLM), vector database, and version control system.

[0052] Embodiment 1

[0053] Continue to refer Figure 2 , shows a flow chart of an embodiment of the code conversion method of the present invention. The code conversion method comprises the following steps:

[0054] Step S1, obtaining source code and target language.

[0055] In this embodiment, the electronic device (e.g., server / terminal device) on which the code conversion method is running can receive the code conversion request via a wired connection or a wireless connection. It should be noted that the above wireless connection method may include but is not limited to 3G / 4G / 5G connection, WiFi connection, Bluetooth connection, WiMAXX connection, Zigbee connection, UWB (ultra wideband) connection, and other wireless connection methods currently known or to be developed in the future.

[0056] In this embodiment, step S1, obtaining source code and target language may further include the following steps:

[0057] S11, obtain the source code from the code repository.

[0058] For example, you can obtain the source code by accessing the URL address of the source code repository through the web interface. If the code repository is stored locally, you can obtain the source code from the local code repository. For example, you can use a version control system (such as Git) to clone or pull the code repository.

[0059] S12, obtaining the target language from the input interface.

[0060] Get the target language from an input interface such as a text box.

[0061] S13, stores source code and target language.

[0062] The acquired source code and target language information are stored.

[0063] Step S2, parse the source code and generate an abstract syntax tree.

[0064] An abstract syntax tree (AST) is a tree-like data structure in which each node represents a grammatical structure in the source code. The relationship between nodes is represented by tree connections, such as parent nodes and child nodes, sibling nodes, etc. It enables the compiler to analyze and process the code more conveniently.

[0065] In specific implementation, Tree-sitter may be used to parse the source code.

[0066] In this embodiment, step S2, parsing the source code and generating an abstract syntax tree, may further include the following steps:

[0067] S21, performs lexical analysis on the source code, divides the character sequence of the source code into lexical units, and assigns a corresponding label to each lexical unit.

[0068] Lexical analysis is the first step in parsing source code, which divides the character sequence of the source code into a series of lexical units (tokens). These lexical units include identifiers, keywords, operators, etc. The lexical analyzer scans the source code, identifies these lexical units, and assigns corresponding labels to each lexical unit.

[0069] For example, in C++ code, the lexical analyzer will recognize lexical units such as `int`, `main`, `{`,}, and mark them as keywords, identifiers, symbols, etc.

[0070] S22, based on the lexical analysis, uses the syntax analyzer to identify the grammatical structure and construct an abstract syntax tree.

[0071] Taking C++ code as an example, the parser will identify grammatical structures such as function declarations, variable declarations, and assignment expressions, and convert them into nodes in AST. For example, the following C++ code:

[0072]

[0073] The corresponding abstract syntax tree AST (simplified representation) is as follows:

[0074] Program

[0075] └──FunctionDeclaration(main)

[0076] ├──Declaration(a)

[0077] │├──TypeSpecifier(int)

[0078] │└──AssignmentExpression

[0079] │├──Identifier(a)

[0080] │└──Constant(

[0081] ├──Declaration(b)

[0082] │├──TypeSpecifier(int)

[0083] │└──AssignmentExpression

[0084] │├──Identifier(b)

[0085] │└──Constant(10)

[0086] ├──Declaration(c)

[0087] │├──TypeSpecifier(int)

[0088] │└──AssignmentExpression

[0089] │├──Identifier(c)

[0090] │└──BinaryExpression(+)

[0091] │├──Identifier(a)

[0092] │└──Identifier(b)

[0093] └──FunctionCall(printf)

[0094] ├──Constant(The sum of a and b is%dn)

[0095] └──Identifier(c)

[0096] In this AST, each node represents a syntactic construct in the source code, such as a variable declaration, assignment expression, binary expression, function declaration, etc.

[0097] For example, use Tree-sitter to parse code and handle the syntax features of different programming languages. Sample code:

[0098]

[0099] Step S3, analyzing the abstract syntax tree to extract semantic information.

[0100] In this embodiment, step S3, analyzing the abstract syntax tree and extracting semantic information may further include the following steps:

[0101] S31, statically check the abstract syntax tree to verify the semantic correctness of the code.

[0102] Perform static checks on the abstract syntax tree, including type checking, scope analysis, etc., to ensure the semantic correctness of the code.

[0103] S32, optimize the abstract syntax tree to improve the execution efficiency of the program.

[0104] The abstract syntax tree AST is optimized through constant folding, dead code elimination and other optimization methods.

[0105] S33, traverses each node of the abstract syntax tree, processes the syntax structure, and extracts semantic information.

[0106] Use the visitor pattern or iterator pattern to traverse the abstract syntax tree AST. The semantic analyzer traverses the abstract syntax tree to check whether the definition and use of variables, functions, and types are consistent, and whether there are semantic errors such as type mismatch and undeclared variables.

[0107] It should be noted that during the semantic analysis process, a symbol table needs to be built and maintained to store information such as variables, functions, types, etc., and to perform checks such as duplicate definitions and type matching.

[0108] Step S4, converting the code into the target language according to the semantic information and the grammatical rules of the target language to obtain a preliminary converted code.

[0109] In this embodiment, step S4, converting the code into the target language according to the semantic information and the grammatical rules of the target language to obtain the preliminary converted code may also specifically include the following steps:

[0110] S41, selecting a conversion template according to the grammatical rules and semantic information of the target language.

[0111] Build a transformation template library containing various common code patterns. These transformation templates should be designed according to the grammatical rules of the target language. According to the grammatical rules and semantic information of the target language, select the most appropriate transformation template from the template library. Select through pattern matching, rule reasoning, etc.

[0112] By accurately analyzing the grammatical rules and semantic information of the target language, it can be ensured that the selected conversion template is consistent with the logic of the source code. The use of templates can greatly reduce the workload of manual code writing, increase the conversion speed, and improve the efficiency of code conversion. The design of the template library makes the code conversion process more modular and maintainable.

[0113] S42, filling the semantic information into the conversion template, generating the source code of the target language, and obtaining the preliminary conversion code.

[0114] Map variable names, data types and other information in the source code to the corresponding variables and data types in the target language. Map control flow statements (such as loops, conditional judgments) in the source code to the corresponding statements in the target language.

[0115] Fill the mapped semantic information into the selected template, such as string replacement, code snippet concatenation, etc.

[0116] It should be noted that the generated code needs to be syntax checked to ensure that it complies with the grammatical rules of the target language.

[0117] Step S5, further optimizing the preliminary conversion code to generate the final translation code.

[0118] The goal of optimizing the generated preliminary conversion code is to improve its performance, readability, and maintainability.

[0119] In this embodiment, step S5, further optimizing the preliminary conversion code to generate the final translation code may further include the following steps:

[0120] S51, pass the preliminary conversion code to the GPT-4 model.

[0121] The preliminary conversion code is input into the GPT-4 model through the GPT-4 model's interactive interface, API or online platform.

[0122] S52, the GPT-4 model analyzes the preliminary conversion code and generates optimization suggestions.

[0123] The GPT-4 model further analyzes and optimizes the initially converted code based on its natural language processing and code generation capabilities.

[0124] After receiving the preliminary converted code, GPT-4 uses its deep learning and pattern recognition capabilities to conduct a detailed analysis of the preliminary converted code. It can identify potential errors, inconsistencies, and possible optimization points in the code. Then, GPT-4 will generate optimized code suggestions, which include more concise syntax, more efficient algorithm implementation, etc.

[0125] S53, applying the optimization suggestions to the preliminary conversion code to generate the final translation code.

[0126] After receiving the code suggestions generated by GPT-4, they can be evaluated and adjusted. If the suggestions are reasonable and effective, they are incorporated into the preliminary conversion code to generate the final translation code. This process improves the accuracy of code conversion.

[0127] Generates transpiled code based on the target language's syntax, preserving code formatting and comments.

[0128] During the code optimization process, you can also define and execute configurable transformation workflow managers to handle exceptions and perform error recovery. Infer the types of variables and expressions based on context information. Use rule engines and machine learning models to transform identifier naming styles. Apply language optimization patterns, such as removing redundant code.

[0129] Integrate the GPT-4 model for code optimization example code:

[0130]

[0131] The sample conversion process code is as follows:

[0132]

[0133]

[0134] In some optional implementations of this embodiment, after step S5, the electronic device may further perform the following steps:

[0135] S6, displays a comparison view of the original code and the translated code on the web interface.

[0136] Feedback from users can be collected through the web interface to improve the transcoding rules.

[0137] In some optional implementations of this embodiment, after step S5, the electronic device may further perform the following steps:

[0138] Step S7, executing the translated code in the target language environment to obtain the translated code execution result.

[0139] Configure the target environment and ensure that the runtime environment required by the target language has been installed and configured correctly. For example, for Python, you need to install the Python interpreter.

[0140] Execute the translated code and run the generated code in the target environment. For the above Python code, you can execute it in the command line:

[0141] python hello.py

[0142] Get the execution result and observe the result of the code execution. In the above example, "Hello, World!" will be output in the console.

[0143] Analyzing the execution results, you can perform functional verification to verify whether the converted code implements the same functions as the source code. For the above example, as long as the output is correct, it means that the functional verification is passed. You can also perform performance analysis on the converted code. Use performance analysis tools (such as cProfile in Python) to find potential performance bottlenecks. You can also pay attention to the memory usage of the code to ensure that there are no memory leaks or other resource waste issues. In Python, you can use memory analysis tools (such as memory_profiler) to check memory usage. You can also perform error handling: check whether the converted code properly handles all possible error conditions. For example, for input data validation, exception handling, etc. You can also evaluate code readability and evaluate whether the converted code is easy to read and maintain. Good code structure and clear logic are essential for long-term maintenance. You can also perform unit testing on the converted code to ensure high code coverage. This helps to find potential bugs and unhandled exceptions. You can also compare the converted code with the source code to find optimization points. For example, in Python, list comprehensions can be used to optimize loop operations.

[0144] During specific implementation, a detailed feature mapping table can be established to target the feature differences between different programming languages, such as memory management and concurrency models, and provide alternative implementations for features that have no direct corresponding features.

[0145] For some transformations that need to consider a wider range of code contexts, data flow analysis and symbol tables can be used to capture and utilize context information.

[0146] In cases where automatically generated code may lack readability, an intelligent formatting algorithm can be used to preserve the comments and structure of the original code.

[0147] For cases where the source code may use language-specific libraries and there is no direct counterpart in the target language, a custom mapping interface can be provided by establishing mapping relationships for commonly used libraries.

[0148] In the case where the performance of the translated code may degrade, the target language can be integrated and a machine learning model can be used to make performance optimization recommendations.

[0149] In specific implementation, in order to convert multi-file project codes, you can import multi-file projects through recursive directory scanning and batch conversion. You can also add Git integration to support importing and exporting code directly from the repository for version control integration. You can also provide a RESTful API to allow other services to call the translation function and provide API services. Allow users to define and share custom conversion rules and set up a custom rule engine. You can also use Docker containerized applications to ensure environmental consistency. Use CI / CD pipelines for automatic testing and deployment updates. Use Kubernetes for container orchestration to achieve high availability and automatic scaling.

[0150] The beneficial effects of implementing this embodiment are as follows: by first obtaining the source code and the target language, parsing the source code, and generating an abstract syntax tree; then analyzing the abstract syntax tree and extracting semantic information; then converting the code to the target language according to the semantic information and the grammatical rules of the target language to obtain a preliminary conversion code; then further optimizing the preliminary conversion code to generate the final translated code; the high degree of automation greatly reduces the workload of manual conversion; the conversion process is standardized and unified, which improves the consistency and accuracy of code conversion; by parsing and analyzing AST, the source code can be understood more deeply, thereby generating higher quality translated code; it is easy to expand and maintain, and support for new languages ​​or features can be added as needed; the optimization step ensures that the converted code is not only correct, but also efficient and readable; it promotes cross-language programming and code reuse, and reduces software development costs; it provides strong tool support for cross-language migration and upgrading of software systems, greatly reduces development costs, and improves the efficiency of software maintenance and evolution.

[0151] The present invention can be used in many general or special computer system environments or configurations. For example: personal computers, server computers, handheld or portable devices, tablet devices, multiprocessor systems, microprocessor-based systems, set-top boxes, programmable consumer electronic devices, network PCs, minicomputers, mainframe computers, distributed computing environments including any of the above systems or devices, etc. The present invention can be described in the general context of computer-executable instructions executed by a computer, such as program modules. Generally, program modules include routines, programs, objects, components, data structures, etc. that perform specific tasks or implement specific abstract data types. The present invention can also be practiced in distributed computing environments, in which tasks are performed by remote processing devices connected through a communication network. In a distributed computing environment, program modules can be located in local and remote computer storage media including storage devices.

[0152] Those skilled in the art can understand that all or part of the processes in the above-mentioned embodiments can be implemented by instructing the relevant hardware through computer-readable instructions, and the computer-readable instructions can be stored in a computer-readable storage medium. When the program is executed, it can include the processes of the embodiments of the above-mentioned methods. Among them, the aforementioned storage medium can be a non-volatile storage medium such as a disk, an optical disk, a read-only memory (ROM), or a random access memory (RAM).

[0153] It should be understood that, although the steps in the flowchart of the accompanying drawings are displayed in sequence as indicated by the arrows, these steps are not necessarily executed in sequence in the order indicated by the arrows. Unless otherwise specified herein, there is no strict order restriction on the execution of these steps, and they can be executed in other orders. Moreover, at least a part of the steps in the flowchart of the accompanying drawings may include multiple sub-steps or multiple stages, and these sub-steps or stages are not necessarily executed at the same time, but can be executed at different times, and their execution order is not necessarily sequential, but can be executed in turn or alternately with other steps or at least a part of the sub-steps or stages of other steps.

[0154] Embodiment 2

[0155] Further references Figure 3 , as a response to the above Figure 2 The present invention provides an embodiment of a code conversion device, which is similar to Figure 2 Corresponding to the method embodiment shown, the device can be specifically applied to various electronic devices.

[0156] like Figure 3 As shown, the code conversion device 60 of this embodiment includes: an acquisition module 61, a parsing module 62, an extraction module 63, a conversion module 64 and an optimization module 65. Among them:

[0157] An acquisition module 61 is used to acquire source code and target language;

[0158] A parsing module 62, used to parse the source code and generate an abstract syntax tree;

[0159] An extraction module 63, used for analyzing the abstract syntax tree and extracting semantic information;

[0160] A conversion module 64, used to convert the code into a target language according to the semantic information and the grammatical conversion rules to obtain a preliminary conversion code;

[0161] The optimization module 65 is used to further optimize the preliminary conversion code to generate the final translation code.

[0162] The beneficial effects of implementing this embodiment are as follows: by first obtaining the source code and the target language, parsing the source code, and generating an abstract syntax tree; then analyzing the abstract syntax tree and extracting semantic information; then converting the code to the target language according to the semantic information and the grammatical rules of the target language to obtain a preliminary conversion code; then further optimizing the preliminary conversion code to generate the final translated code; the high degree of automation greatly reduces the workload of manual conversion; the conversion process is standardized and unified, which improves the consistency and accuracy of code conversion; by parsing and analyzing AST, the source code can be understood more deeply, thereby generating higher quality translated code; it is easy to expand and maintain, and support for new languages ​​or features can be added as needed; the optimization step ensures that the converted code is not only correct, but also efficient and readable; it promotes cross-language programming and code reuse, and reduces software development costs; it provides strong tool support for cross-language migration and upgrading of software systems, greatly reduces development costs, and improves the efficiency of software maintenance and evolution.

[0163] Embodiment 3

[0164] The present invention also provides an embodiment of a code conversion device, the device embodiment is Figure 2 Corresponding to the method embodiment shown, the device can be specifically applied to various electronic devices.

[0165] A code conversion device of this embodiment adopts a modular design and includes a code parsing module, a semantic analysis module, a conversion rule engine, a code generation module and a workflow manager.

[0166] The front end features a web interface that can be implemented using React or Vue.js.

[0167] The backend uses Python service and can be implemented using FastAPI or Flask.

[0168] The code parsing module can use Tree-sitter to parse the source code and generate an abstract syntax tree (AST).

[0169] The semantic analysis module is used to analyze AST and extract the semantic information of the code.

[0170] The transformation rules engine is used to define and apply transformation rules from source language to target language.

[0171] The AI ​​enhancement module, based on the Langchain framework, uses models such as GPT-4 to optimize conversion results.

[0172] The code generation module generates target language code based on the converted AST.

[0173] The workflow manager is used to coordinate the work of each module, manage the entire code conversion process, define and execute configurable conversion workflows, handle exceptions and perform error recovery.

[0174] Data storage, using PostgreSQL to store conversion history and user feedback information.

[0175] The code conversion device of this embodiment integrates an AI enhancement module based on the Langchain framework, and uses large language models such as GPT-4 to optimize code conversion. Tree-sitter is used for efficient code parsing, which improves the support for various programming languages. A customizable conversion rule engine is implemented to support user-defined conversion logic.

[0176] The code conversion device of this embodiment is provided with a code optimization module based on machine learning, which can learn and apply programming patterns and best practices.

[0177] Through these settings, the device can accurately understand the structure and semantics of the source code and generate code that conforms to the habits of the target language.

[0178] Figure 4 FIG. 2 is a timing diagram of the components of another code conversion device of the present invention. Figure 4 As shown, the timing of the constituent modules of the code conversion device is as follows:

[0179] The user enters the source code and target language through a web interface.

[0180] The code parsing module uses Tree-sitter to parse the source code, perform efficient code parsing, process the grammatical features of different programming languages, and generate an abstract syntax tree AST.

[0181] Sample code:

[0182]

[0183] The semantic analysis module performs type inference and symbol parsing, analyzes variable scope and data flow, analyzes the abstract syntax tree AST, and extracts semantic information.

[0184] The conversion rule engine defines mapping rules between languages, supports user-defined rules, applies predefined grammar conversion rules, and handles basic language conversion.

[0185] The AI ​​enhancement module uses a custom chain built by Langchain to process complex logic conversions. The preliminary conversion results are passed to the GPT-4 model for further optimization.

[0186] Sample code:

[0187]

[0188]

[0189] The code generation module generates code based on the syntax of the target language, maintains the code format and comments, merges the output of the Tree-sitter and AI enhancement modules, and generates the final translated code.

[0190] A comparison view of the original code and the translated code is displayed on the web interface.

[0191] Collect user feedback to improve conversion rules and AI prompts.

[0192] AST transformation algorithm,recursively traverses the source AST and applies transformation rules to generate the target AST.

[0193] Type inference algorithms infer the types of variables and expressions based on contextual information.

[0194] Naming convention transformation, using a rules engine and machine learning models to transform identifier naming styles.

[0195] Code optimization algorithms that apply language-specific optimization techniques, such as removing redundant code.

[0196] Example conversion process:

[0197]

[0198]

[0199] The implementation of this embodiment has the following beneficial effects: high efficiency, significantly improving code conversion efficiency through automated workflows and AI assistance; high accuracy, combining static analysis, machine learning and large language models to improve conversion accuracy; strong scalability, modular design and configurable workflows support easy addition of new languages ​​and features; high intelligence, the AI ​​enhancement module continuously learns and improves conversion quality to adapt to different programming styles and patterns; strong customizability, supporting users to customize conversion rules and optimization strategies to meet specific needs; high consistency, ensuring that the converted code complies with the best practices and coding specifications of the target language; cross-platform support, the Web interface and API services make the system easy to integrate into various development environments; version control-friendly, integrated with version control systems such as Git, to facilitate management of code conversion for large projects; strong continuous optimization performance, continuously improving system performance and code conversion quality through user feedback mechanism; provides strong tool support for cross-language migration and upgrade of software systems, greatly reduces development costs, and improves the efficiency of software maintenance and evolution.

[0200] Embodiment 4

[0201] To solve the above technical problems, the embodiment of the present invention also provides a computer device. Figure 5 , Figure 5 This is a basic structural block diagram of the computer device in this embodiment.

[0202] The computer device 7 includes a memory 71, a processor 72, and a network interface 73 that are interconnected through a system bus. It should be noted that the figure only shows a computer device 7 having components of a memory 71, a processor 72, and a network interface 73, but it should be understood that it is not required to implement all the components shown, and more or fewer components may be implemented instead. Among them, those skilled in the art can understand that the computer device here is a device that can automatically perform numerical calculations and / or information processing according to pre-set or stored instructions, and its hardware includes but is not limited to a microprocessor, an application specific integrated circuit (ASIC), a field programmable gate array (FPGA), a digital processor (DSP), an embedded device, etc.

[0203] The computer device may be a desktop computer, a notebook computer, a PDA, a cloud server, etc. The computer device may interact with the user through a keyboard, a mouse, a remote control, a touch pad, or a voice control device.

[0204] The memory 71 includes at least one type of readable storage medium, and the readable storage medium includes flash memory, hard disk, multimedia card, card-type memory (for example, SD or DX memory, etc.), random access memory (RAM), static random access memory (SRAM), read-only memory (ROM), electrically erasable programmable read-only memory (EEPROM), programmable read-only memory (PROM), magnetic memory, disk, optical disk, etc. In some embodiments, the memory 71 may be an internal storage unit of the computer device 7, such as a hard disk or memory of the computer device 7. In other embodiments, the memory 71 may also be an external storage device of the computer device 7, such as a plug-in hard disk, a smart memory card (Smart Media Card, SMC), a secure digital (Secure Digital, SD) card, a flash card (FlashCard), etc. equipped on the computer device 7. Of course, the memory 71 may also include both the internal storage unit of the computer device 7 and its external storage device. In this embodiment, the memory 71 is generally used to store the operating system and various application software installed on the computer device 7, such as computer-readable instructions of the code conversion method, etc. In addition, the memory 71 can also be used to temporarily store various types of data that have been output or are to be output.

[0205] The processor 72 may be a central processing unit (CPU), a controller, a microcontroller, a microprocessor, or other data processing chips in some embodiments. The processor 72 is generally used to control the overall operation of the computer device 7. In this embodiment, the processor 72 is used to run the computer-readable instructions stored in the memory 71 or process data, such as computer-readable instructions for running the code conversion method.

[0206] The network interface 73 may include a wireless network interface or a wired network interface. The network interface 73 is generally used to establish a communication connection between the computer device 7 and other electronic devices.

[0207] The implementation of this embodiment has the following beneficial effects: a high degree of automation, which greatly reduces the workload of manual conversion; the conversion process is standardized and unified, which improves the consistency and accuracy of code conversion; by parsing and analyzing AST, it is possible to have a deeper understanding of the source code, thereby generating higher quality translated code; it is easy to expand and maintain, and support for new languages ​​or features can be added as needed; the optimization steps ensure that the converted code is not only correct, but also efficient and readable; it promotes cross-language programming and code reuse, and reduces software development costs; it provides strong tool support for cross-language migration and upgrading of software systems, greatly reduces development costs, and improves the efficiency of software maintenance and evolution.

[0208] Embodiment 5

[0209] The present invention also provides another embodiment, namely, providing a computer-readable storage medium, wherein the computer-readable storage medium stores computer-readable instructions, and the computer-readable instructions can be executed by at least one processor to enable the at least one processor to perform the steps of the code conversion method as described above.

[0210] The implementation of this embodiment has the following beneficial effects: a high degree of automation, which greatly reduces the workload of manual conversion; the conversion process is standardized and unified, which improves the consistency and accuracy of code conversion; by parsing and analyzing AST, it is possible to have a deeper understanding of the source code, thereby generating higher quality translated code; it is easy to expand and maintain, and support for new languages ​​or features can be added as needed; the optimization steps ensure that the converted code is not only correct, but also efficient and readable; it promotes cross-language programming and code reuse, and reduces software development costs; it provides strong tool support for cross-language migration and upgrading of software systems, greatly reduces development costs, and improves the efficiency of software maintenance and evolution.

[0211] Through the description of the above implementation methods, those skilled in the art can clearly understand that the above-mentioned embodiment methods can be implemented by means of software plus a necessary general hardware platform, and of course can also be implemented by hardware, but in many cases the former is a better implementation method. Based on such an understanding, the technical solution of the present invention is essentially or the part that contributes to the prior art can be embodied in the form of a software product, which is stored in a storage medium (such as ROM / RAM, a magnetic disk, or an optical disk), and includes a number of instructions for a terminal device (which can be a mobile phone, a computer, a server, an air conditioner, or a network device, etc.) to execute the various embodiment methods of the present invention.

[0212] Obviously, the embodiments described above are only some embodiments of the present invention, rather than all embodiments. The preferred embodiments of the present invention are given in the accompanying drawings, but they do not limit the patent scope of the present invention. The present invention can be implemented in many different forms. On the contrary, the purpose of providing these embodiments is to make the understanding of the disclosure of the present invention more thorough and comprehensive. Although the present invention has been described in detail with reference to the aforementioned embodiments, for those skilled in the art, it is still possible to modify the technical solutions recorded in the aforementioned specific embodiments, or to perform equivalent replacements for some of the technical features therein. Any equivalent structure made using the contents of the specification and drawings of the present invention, directly or indirectly used in other related technical fields, is also within the scope of patent protection of the present invention.

Claims

1. A code conversion method, characterized in that: The steps include: Obtain source code and target language; Parsing the source code to generate an abstract syntax tree; Analyze the abstract syntax tree to extract semantic information; According to the semantic information and the grammatical rules of the target language, the code is converted into the target language to obtain a preliminary conversion code; The preliminary conversion code is further optimized to generate a final translation code.

2. The code conversion method according to claim 1, characterized in that: The steps of obtaining source code and target language specifically include: Obtain the source code from a code repository; Acquire the target language from an input interface; The source code and the target language are stored.

3. The code conversion method according to claim 1, characterized in that: The step of parsing the source code and generating an abstract syntax tree specifically includes: Performing lexical analysis on the source code, dividing the character sequence of the source code into lexical units, and assigning a corresponding label to each lexical unit; Based on the lexical analysis, the syntax analyzer is used to identify the grammatical structure and construct an abstract syntax tree.

4. The code conversion method according to claim 1, characterized in that: The step of analyzing the abstract syntax tree and extracting semantic information specifically includes: Perform static checking on the abstract syntax tree to verify the semantic correctness of the code; Optimize the abstract syntax tree to improve the execution efficiency of the program; Each node of the abstract syntax tree is traversed, and the syntax structure is processed to extract the semantic information.

5. The code conversion method according to claim 1, characterized in that: The step of converting the code into the target language according to the semantic information and the grammatical rules of the target language to obtain the preliminary converted code specifically includes: Selecting a conversion template according to the grammatical rules of the target language and the semantic information; The semantic information is filled into the conversion template to generate source code of the target language to obtain a preliminary conversion code.

6. The code conversion method according to claim 1, characterized in that: The step of further optimizing the preliminary conversion code to generate the final translation code specifically includes: Passing the preliminary transformation code to the GPT-4 model; The GPT-4 model analyzes the preliminary conversion code and generates optimization suggestions; Apply the optimization suggestion to the preliminary conversion code to generate a final translation code.

7. The code conversion method according to any one of claims 1 to 6, characterized in that: After the step of further optimizing the preliminary conversion code to generate the final translation code, the method further includes: In the target language environment, the translated code is executed to obtain a translated code execution result.

8. A code conversion device, characterized in that: include: Acquisition module, used to obtain source code and target language; A parsing module, used for parsing the source code and generating an abstract syntax tree; An extraction module, used for analyzing the abstract syntax tree and extracting semantic information; A conversion module, used to convert the code into a target language according to the semantic information and grammar conversion rules to obtain a preliminary conversion code; The optimization module is used to further optimize the preliminary conversion code to generate a final translation code.

9. A computer device, comprising a memory and a processor, wherein the memory stores computer-readable instructions, and the processor implements the steps of the code conversion method according to any one of claims 1 to 7 when executing the computer-readable instructions.

10. A computer-readable storage medium, characterized in that: The computer-readable storage medium stores computer-readable instructions, and when the computer-readable instructions are executed by a processor, the steps of the code conversion method according to any one of claims 1 to 7 are implemented.

Citation Information

Patent Citations

  • Text programming language compiling method based on decoupling architecture

    CN116501330A

  • Multi-language compiling method, system and device and computer storage medium

    CN116737161A

  • Code processing method and device, electronic equipment and storage medium

    CN117971231A

  • Dynamic code generation method and system based on interface document

    CN118860356A

  • Multi-modal program inference

    US20230176829A1

Cited By

  • Programming assistance method based on generative AI, computer equipment and storage medium

    CN120010825A

  • Method, apparatus, device and product for introducing signal in code

    CN120315690A

  • Method, apparatus, device and product for introducing signals into code

    CN120315690B

  • Python-oriented Data + AI unified compiling optimization method

    CN122086410A

  • Method and device for code conversion, equipment, storage medium and program product

    CN122489078A