Code conversion method, device, electronic device and computer-readable storage medium

By building a source syntax framework and matching target keywords, the automatic conversion of code is achieved, which solves the problem of low code transplantation efficiency in the existing technology and improves the efficiency and accuracy of code conversion.

CN120085874BActive Publication Date: 2025-09-09SHENZHEN XINRUN FULIAN DIGITAL TECH CO LTD +1
View PDF 2 Cites 0 Cited by

Patent Information

Application Number
CN202510566853.X
Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-04-30
Publication Date
2025-09-09
Estimated Expiration
2045-04-30

AI Technical Summary

Technical Problem

The code migration process in existing technologies is inefficient, relies on manual analysis and high requirements of developers, and is difficult to efficiently complete the conversion of code from one language to another.

Method used

By obtaining source keywords in the source code, building a source grammar framework, and matching target keywords in the target language, automatic code conversion is achieved, including exception checking and optimization operations.

Benefits of technology

It realizes the automatic conversion of code, improves the efficiency and accuracy of code transplantation, and reduces the dependence on developers.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN120085874B_ABST
    Figure CN120085874B_ABST
Patent Text Reader

Abstract

The present invention proposes a code conversion method, device, electronic device, and computer-readable storage medium. The method includes the following steps: obtaining source code and matching source keywords in the source code; constructing a source grammar framework corresponding to the source code based on the source keywords, and determining the grammar body contained in the source grammar framework; matching target keywords corresponding to the grammar body in a target keyword library, wherein the target keywords are keywords corresponding to the target language type; and translating the code corresponding to the grammar body in the source code using the target keywords to obtain target code. Constructing the source grammar framework using the source keywords in the source code enables the overall code structure of the source code to be determined. Simultaneously, the execution logic of the source code can be determined based on the grammar body in the source grammar framework. This allows the target keywords based on the source grammar framework and the grammar body to accurately translate the source code and obtain the target code, thereby achieving automatic code conversion.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] The present invention relates to the field of computers, and in particular to a code conversion method, device, electronic device, and computer-readable storage medium. Background Art

[0002] Computer programs generate large amounts of business data during operation. For businesses and even individuals, this data is often the key to survival and part of their core assets, making data storage crucial. Relational database systems are commonly used in the industry to store structured data.

[0003] During the development process, different types of code need to be ported based on different application needs. For example, to improve the efficiency of mutual collaboration or enhance the maintainability of the code, a large amount of original PL / pgSQL-based code is ported to a high-level programming language. To improve data security, code developed based on a high-level programming language and containing a large amount of data operation logic is ported to PL / pgSQL (code written in the target language).

[0004] The existing solution is for developers to manually analyze the source code, design the program architecture, and use the target language to write the program running logic in the source language to complete the code translation process. This has high requirements for developers and is inefficient. Summary of the Invention

[0005] The main purpose of the present invention is to provide a code conversion method, device, electronic device and computer-readable storage medium, aiming to solve the problem of inconvenience in code transplantation in the prior art.

[0006] To achieve the above object, the present invention provides a code conversion method, which includes the following steps:

[0007] Obtaining source code and matching source keywords in the source code;

[0008] Constructing a source grammar framework corresponding to the source code according to the source keyword, and determining a grammar body included in the source grammar framework;

[0009] Matching a target keyword corresponding to the grammatical body in a target keyword library, wherein the target keyword is a keyword corresponding to the target language type;

[0010] The code corresponding to the grammatical body in the source code is translated using the target keyword to obtain a target code.

[0011] Optionally, obtaining source code and matching source keywords in the source code includes:

[0012] Obtaining the source code and obtaining a source grammar standard corresponding to the source language type;

[0013] performing anomaly checking on the source code according to the source syntax standard to determine whether the source code complies with the source syntax standard;

[0014] If the source code complies with the source syntax standard, a source keyword is matched in the source code.

[0015] Optionally, obtaining source code and matching source keywords in the source code includes:

[0016] Obtain the source code and a source keyword library corresponding to the source language type;

[0017] The source keywords included in the source keyword library are matched sequentially in the source code from top to bottom.

[0018] Optionally, constructing a source grammar framework corresponding to the source code according to the source keyword includes:

[0019] Positioning the source keywords from top to bottom;

[0020] A source grammar node is determined based on the association relationship of the source keywords to obtain the source grammar framework.

[0021] Optionally, determining the grammatical body included in the source grammatical framework includes:

[0022] Determine the optimization direction of code conversion;

[0023] Performing an optimization operation on the source grammar framework according to the optimization direction;

[0024] The grammatical body is determined according to the source grammatical framework after the optimization operation.

[0025] Optionally, after determining the grammatical body included in the source grammatical framework, the method further includes:

[0026] Determining whether the source grammar framework contains the grammar body corresponding to database processing;

[0027] If the source grammar framework does not include the grammar body corresponding to the database processing, the conversion operation on the source code is exited.

[0028] Optionally, after obtaining the target code, the method further includes:

[0029] Testing the target code and determining whether the test result indicates that the target code has an anomaly;

[0030] If the test result indicates that the target code has an abnormality, the abnormal code in the target code is modified according to the abnormality information.

[0031] To achieve the above object, the present invention further provides a code conversion device, the code conversion device comprising:

[0032] A first acquisition module is used to acquire source code and match source keywords in the source code;

[0033] A first construction module is configured to construct a source grammar framework corresponding to the source code according to the source keyword, and determine a grammar body included in the source grammar framework;

[0034] A first matching module is configured to match a target keyword corresponding to the grammatical body in a target keyword library, wherein the target keyword is a keyword corresponding to a target language type;

[0035] The first translation module is configured to translate the code corresponding to the grammatical body in the source code using the target keyword to obtain a target code.

[0036] To achieve the above objectives, the present invention also provides an electronic device, which includes a memory, a processor, and a computer program stored in the memory and executable on the processor, wherein the computer program implements the steps of the above-mentioned code conversion method when executed by the processor.

[0037] To achieve the above object, the present invention further provides a computer-readable storage medium having a computer program stored thereon. When the computer program is executed by a processor, the steps of the code conversion method described above are implemented.

[0038] The present invention proposes a code conversion method, device, electronic device, and computer-readable storage medium, which obtains source code and matches source keywords in the source code; constructs a source grammar framework corresponding to the source code based on the source keywords, and determines the grammar body contained in the source grammar framework; matches target keywords corresponding to the grammar body in a target keyword library, wherein the target keywords are keywords corresponding to the target language type; and translates the code corresponding to the grammar body in the source code using the target keywords to obtain the target code. By constructing the source grammar framework using the source keywords in the source code, the overall code structure of the source code can be determined. At the same time, the execution logic of the source code can be determined based on the grammar body in the source grammar framework, so that the target keywords based on the source grammar framework and the grammar body can accurately translate the source code to obtain the target code, thereby achieving automatic code conversion. BRIEF DESCRIPTION OF THE DRAWINGS

[0039] Figure 1 Schematic diagram of the flow of the first embodiment of the code conversion method of the present invention;

[0040] Figure 2 Schematic diagram of the overall process of the code conversion method of the present invention;

[0041] Figure 3 This is a flow chart for a specific code in an embodiment of a code conversion method of the present invention;

[0042] Figure 4 It is a schematic diagram of the module structure of the electronic device of the present invention. DETAILED DESCRIPTION

[0043] It should be understood that the specific embodiments described herein are only used to explain the present invention and are not intended to limit the present invention.

[0044] The present invention provides a code conversion method, referring to Figure 1 , Figure 1 This is a flow chart of a first embodiment of a code conversion method according to the present invention, wherein the method comprises the following steps:

[0045] Step S10, obtaining source code, and matching source keywords in the source code;

[0046] Source code is the code to be converted; in contrast, target code is the code obtained by converting the source code. The specific types of source code and target code can be set based on actual application needs; for example, if the source code is written in PL / pgSQL, the target code can be written in a high-level programming language such as Java, Python, Go, or C#; or if the source code is written in a high-level programming language such as Java, Python, Go, or C#, the target code can be written in PL / pgSQL.

[0047] Source keywords are keywords in the source code. It can be understood that keywords are code characters that indicate statement types. Different language types correspond to different keywords. For example, statement types include but are not limited to conditional judgment statements (corresponding keywords: if...else, case...when) and derivative syntax bodies with the same function, switch statements (corresponding keywords: switchcase) and derivative syntax bodies with the same function, loop statements (corresponding keywords: while, for, do, loop) and derivative syntax bodies with the same function, return statements (corresponding keywords: return, exit...when) and derivative syntax bodies with the same function, logical judgments (corresponding keywords: in, not, and, or) and derivative syntax bodies with the same function, loop exit statements (corresponding keywords: break, continue, return) and derivative syntax bodies with the same function, exception handling statements (corresponding keywords: try, catch, except, else, finally) and derivative syntax bodies with the same function.

[0048] Step S20, constructing a source grammar framework corresponding to the source code according to the source keyword, and determining a grammar body included in the source grammar framework;

[0049] The source syntax frame is used to indicate the overall structure of the source code; the source syntax frame can be specifically a syntax tree. It can be understood that the syntax nodes of the syntax tree can be determined by the source keyword. After all the syntax nodes are determined, the syntax tree, i.e., the source syntax frame, can be obtained.

[0050] The syntax body indicates the specific execution logic and functions of the code; for example, the syntax body can indicate but is not limited to inserting data, modifying data, accumulating counters, printing to the console, sleeping the CPU, etc.; it can be understood that the execution logic corresponding to the syntax body relies on specific source keywords. Therefore, the corresponding syntax body can be determined by analyzing the source keywords and specific codes through the syntax standards corresponding to the language type of the source code; at the same time, after the syntax body is determined, the keywords and code syntax required to implement the corresponding execution logic can also be known.

[0051] Step S30, matching a target keyword corresponding to the grammatical body in a target keyword library, wherein the target keyword is a keyword corresponding to the target language type;

[0052] The target language type is the language type of the target code. The target keyword library contains the keywords used in the target language type.

[0053] It can be understood that the grammatical body indicates the code execution logic and function rather than the specific code; therefore, the grammatical body can indicate the code structure corresponding to the execution logic and function in different language types; therefore, the target keyword corresponding to the source code execution function can be determined through the grammatical body.

[0054] The correspondence between different types of syntax bodies and target keywords can be pre-set. Once the syntax body is determined, the corresponding target keyword can be determined. In other embodiments, the target keyword can also be determined based on the source keyword corresponding to the syntax body, that is, by matching the target keyword with the same function as the source keyword. For example, the loop statement in PL / pgSQL is "loop", while the loop statements in Java and Python are "while" and "for". If the corresponding source keyword in PL / pgSQL contains "loop", the corresponding target keyword in Java can be considered to be "while". The same applies to other types of keywords and will not be further explained.

[0055] Step S40: translating the code corresponding to the grammatical body in the source code using the target keyword to obtain a target code.

[0056] After determining the target keyword, the source code can be translated based on the target keyword. It can be understood that a single grammatical body corresponds to a complete execution logic. Therefore, the grammatical body is used as the translation unit and translated in sequence. After all grammatical bodies are translated, the corresponding target code can be obtained.

[0057] This embodiment constructs a source grammar framework through source keywords in the source code, so that the overall code structure of the source code can be determined. At the same time, the execution logic of the source code can be determined based on the grammar body in the source grammar framework, so that the target keywords based on the source grammar framework and the grammar body can accurately translate the source code to obtain the target code, thereby realizing automatic code conversion.

[0058] Further, see Figure 2 , the step S10 comprises the steps of:

[0059] Step S11, obtaining the source code and obtaining the source grammar standard corresponding to the source language type;

[0060] Step S12, performing anomaly check on the source code according to the source syntax standard to determine whether the source code complies with the source syntax standard;

[0061] Step S13: If the source code meets the source syntax standard, source keywords are matched in the source code.

[0062] If the source code does not conform to the source syntax standard, the actual execution logic may not be determined based on the source code subsequently, resulting in errors in determining the source syntax framework and syntax body. At the same time, the target code converted based on the source code that does not conform to the source syntax standard may also not conform to the target syntax standard. Therefore, in order to avoid major errors in the conversion that affect the conversion efficiency, when the source code does not conform to the source syntax standard, the subsequent conversion operation is stopped, and the exception is reminded so that the developer can process the abnormal part of the source code to make the source code conform to the source syntax standard; when the source code conforms to the source syntax standard, the subsequent conversion process can be executed.

[0063] The source grammar standard can be obtained through the API of the corresponding grammar type.

[0064] Furthermore, the step S10 includes the steps of:

[0065] Step S14, obtaining the source code and obtaining a source keyword library corresponding to the source language type;

[0066] Step S15: matching the source keywords contained in the source keyword library in sequence in the source code from top to bottom.

[0067] The source keyword library contains the keywords used by the source language type.

[0068] It is understandable that a complete execution statement may correspond to multiple keywords, such as in if...else..., if and else are each a keyword; therefore, the order of keywords is important for the grammatical framework. In this embodiment, the source keywords are matched in a top-down manner, thereby retaining the logical relationship between the source keywords.

[0069] Furthermore, the step S20 includes the steps of:

[0070] Step S21, locating the source keywords from top to bottom;

[0071] Step S22: determining source grammar nodes based on the association relationship of the source keywords to obtain the source grammar framework.

[0072] Positioning refers to clarifying the mutual position relationship between source keywords;

[0073] An association relationship refers to the relationship between multiple keywords corresponding to the same execution statement; for example, in if...else..., if and else have an association relationship.

[0074] The source grammar frame is composed of multiple source grammar nodes; therefore, after the source grammar nodes are determined based on the association relationship, the corresponding source grammar frame is obtained after all the source grammar nodes are determined.

[0075] For example, after finding the if keyword, first record the node of the if keyword, and then find and record the else if node or else node corresponding to the if keyword. At the same time, if there are other types of keywords in this syntax node, such as the keyword for corresponding to the loop body structure, you also need to find the corresponding break, return or loop termination keyword and record this syntax node; when the keywords corresponding to different execution statements are nested and used, and so on, until all the source syntax nodes of the source code are determined and the source syntax framework is determined.

[0076] The following example uses PL / pgSQL as the source language, Python as the target language, and Python standard library version 3.7.8 as an example:

[0077] The following code block exists in the source code:

[0078] DO

[0079] $$

[0080] DECLARE

[0081] v_col1 table1.col_1%TYPE := NULL;

[0082] BEGIN

[0083] FOR rec IN SELECT col_1, col_2 FROM schema.table t1

[0084] LEFT JOIN schema.table2 t2 ON t2.wheelid = t1.wheelid

[0085] ORDER BY t1.wheelid DESC

[0086] LOOP

[0087] IF rec.col_1 is null THEN

[0088] -- insert statements;

[0089] v_count_insert := v_count_insert + 1;

[0090] ELSIF rec.col_1 is not null THEN

[0091] -- update statements;

[0092] v_count_update := v_count_update + 1;

[0093] ELSE

[0094] v_count_nothing := v_count_nothing + 1;

[0095] END IF;

[0096] IF v_count_insert<>0 AND v_count_insert % 10000 = 0 THEN

[0097] COMMIT;

[0098] raise notice '% rows insert!' , v_count_insert;

[0099] PERFORM pg_sleep(0.5);

[0100] END IF;

[0101] END LOOP;

[0102] EXCEPTION

[0103] WHEN OTHERS THEN

[0104] ROLLBACK;

[0105] result_code := -999;

[0106] result_msg := SQLERRM;

[0107] RAISE NOTICE '%,%',SQLSTATE, SQLERRM;

[0108] END;

[0109] The execution logic of the above code block is: query the col_1 and col_2 field data after the left outer join of the database table table and table2 table, loop through this data set, if col_1 is null, insert this data into table3, if col_1 is not null, update this data to table2.

[0110] See also Figure 3, the conversion process for the above code block includes:

[0111] Traverse the source code block, determine the keywords one by one, and record the source syntax nodes. For example, the keyword FOR is recorded as FOR_1. Similarly, the following syntax tree nodes are obtained: IN_1, LOOP_1, IF_1, THEN_1, ELSIF_1, ELSE_IF_THEN_1, ELSE_1, END_IF_1, IF_2, AND_2, THEN_2, END_IF_2, END_LOOP_1, EXCEPTION_1, WHEN_1, THEN_1, RAISE_NOTICE_1, etc.

[0112] Once the source syntax nodes are determined, the source syntax framework is determined. The keywords used in the source syntax framework, the syntax nodes corresponding to the keywords, and the grammatical meanings of the keywords are clarified. The source syntax framework is then traversed, starting with a FOR loop, and the source syntax nodes LOOP->IF->ELSIF->ELSE->END IF…EXCEPTION are determined in sequence. Based on the sequential structure of the source syntax nodes, all syntax bodies within the syntax framework are determined. These syntax bodies correspond to commands such as inserting data, modifying data, accumulating counters, printing to the console, and sleeping the CPU. After the syntax bodies are determined, they are translated separately. The translation process includes:

[0113] Find the target keywords corresponding to the source keywords in the Python 3.7.8 standard library, such as IF...ELSIF...ELSE...END IF corresponding to if...elif..else, FOR...IN... corresponding to curosr.execute, LOOP...END LOOP corresponding to for, EXCEPTION...WHEN... corresponding to try...except...finally..., and so on. Generate the target syntax nodes of the target code according to the source syntax nodes of the source code, and then translate the code corresponding to the syntax body in the source code into Python syntax through the target keywords according to the execution logic of the syntax body recorded in the source code. And so on, until all the syntax bodies are translated, the target code is obtained:

[0114] def transfer():

[0115] connection = psycopg2.connect(**connect_kwargs)

[0116] cursor = connection.cursor()

[0117] v_count_insert = 0

[0118] v_count_update = 0

[0119] v_count_nothing = 0

[0120] sql = f"SELECT col_1, col_2 FROM schema.table t1 " \

[0121] f"LEFT JOIN schema.table2 t2 ON t2.wheelid = t1.wheelid " \

[0122] f"ORDER BY t1.wheelid DESC; "

[0123] try:

[0124] cursor.execute(sql)

[0125] if cursor.description is None:

[0126] print("There are no data.")

[0127] return

[0128] resultTupleList = cursor.fetchall()

[0129] for tupleData in resultTupleList:

[0130] v_col1 = tupleData[0]

[0131] v_col2 = tupleData[1]

[0132] if v_col1 is None:

[0133] # insert statements;

[0134] v_count_insert += 1

[0135] elif v_col1 is not None:

[0136] # update statements;

[0137] v_count_update += 1

[0138] else:

[0139] v_count_nothing += 1

[0140] if v_count_insert != 0 and v_count_insert % 10000 == 0:

[0141] connection.commit()

[0142] print(f"{v_count_insert} rows insert!'")

[0143] time.sleep(0.5)

[0144] except Exception as e:

[0145] if connection is not None:

[0146] connection.rollback()

[0147] print(e)

[0148] finally:

[0149] cursor.close()

[0150] Furthermore, the step S20 includes the steps of:

[0151] Step S23, determining the optimization direction of code conversion;

[0152] Step S24, performing an optimization operation on the source grammar framework according to the optimization direction;

[0153] Step S25: determining the grammatical body according to the source grammatical framework after the optimization operation.

[0154] The optimization direction is used to indicate the execution state of the target code that needs to be optimized when it is executed; in this embodiment, the optimization direction includes time complexity and space complexity; time complexity and space complexity often affect each other. When the time complexity requirement is higher, the performance of space complexity may be reduced, that is, it may cause more memory space to be occupied; conversely, when the space complexity requirement is higher, the performance of time complexity may be deteriorated, that is, it may cause a longer running time; whether to optimize for time complexity or space complexity can be set based on the target language type and conversion needs.

[0155] Time complexity is used to describe the relationship between the execution time of an algorithm and the amount of input data. It is expressed as O(n), where n represents the amount of input data. The smaller the time complexity, the less time the algorithm takes to execute. When optimizing for time complexity, specific optimization directions may include:

[0156] 1. Reduce the number of loop iterations: For algorithms with loop structures, the number of code executions within the loop can be minimized. For example, when a condition is met, immediately exit the loop through break or return the result set immediately to avoid multiple useless executions of the subsequent loop body, reduce CPU and memory usage, and thus achieve the goal of reducing time complexity.

[0157] 2. Reduce the number of function calls: The same function should be completed with the least number of calls. For example, there is a function square(n), which is used to calculate the square of the input integer number n. For example, when the input is 2, the output is 4; when the input is 3, the output is 9, and so on... Now when you want to square the elements of an array of length 6 containing the following elements: [1, 2, 3, 3, 3, 4], the value 3 appears three times; at this time, you can judge the element with input 3 before calling the function square(n). If the square of 3 has been calculated, then ignore the next two 3s to avoid repeated calculation of the square of 3, and directly calculate the square of 4; you can also deduplicate the elements in the array, remove the repeated element 3, keep only one 3, and then traverse the calculation. In this way, by reducing the number of function calls, the creation of redundant call stacks is reduced, thereby achieving the purpose of reducing time complexity;

[0158] 3. Reduce the number of memory accesses: Improve the utilization of created objects and reduce the creation of objects; use local variables and avoid frequent use of global variables, because local variables are closer to the memory address, and memory allocation and use are more efficient;

[0159] 4. Avoid repeated calculations: If a calculation is repeated multiple times, its results can be temporarily saved to avoid repeated calculations;

[0160] 5. Recursive algorithm: The function in recursive thinking will call itself to solve smaller sub-problems. At the same time, each sub-problem actually uses the same algorithm, and computers are best at quickly and accurately calculating large amounts of repetitive operations. Therefore, in this process, using recursion instead of loops can effectively reduce the time complexity of the algorithm, but it is important to control the recursive depth. Because each recursive call will generate a new function call stack, which contains information such as local variables and parameters of the current function. These stacks will exist until the recursion is completed and begins to merge and return, and then the stack space will be released in turn. If the recursive depth is very large, that is, when there are many levels of recursive calls, an infinite loop may occur, which will lead to continuous allocation of stack space, resulting in continuous consumption of memory resources while being unable to be released quickly. Over time, this may cause stack overflows and program execution exceptions. Such recursive calls have the hidden danger of excessively high space complexity.

[0161] Space complexity is a measure of the memory space required by an algorithm during execution. It describes how the algorithm's storage requirements change as the problem size grows. The smaller the space complexity, the less memory the algorithm takes up during execution. When memory resources are limited, optimizing space complexity is essential. When optimizing time complexity, specific optimization directions may include:

[0162] 1. In-place algorithm: Try to operate on the original data instead of creating additional data structures (such as arrays, lists, dictionaries, maps and other complex data structures) to store intermediate results. This can save a lot of memory space. For example, in the sorting algorithm, you can use the quick sort algorithm, because quick sort is an in-place sorting algorithm, which achieves sorting by exchanging the positions of elements in the array. It only requires constant space to store the data of temporary variables without taking up additional memory space;

[0163] 2. Iteration instead of recursion: Recursive algorithms usually use a recursive call stack to save state. Although this is more efficient, it will increase space complexity. Therefore, recursive algorithms can be rewritten as iterative algorithms to avoid taking up extra stack space. For tree traversal operations, iterative loops can be used instead of recursion.

[0164] 3. Appropriate data structure: Choosing the right data structure can reduce space complexity. For example, for the problem of storing key-value pairs, using a hash table can provide an average lookup complexity of O(1), while using an array may require a lookup complexity of O(n);

[0165] 4. Cache calculation results: You can save space by caching intermediate calculation results to avoid repeated calculations. This can be achieved through an array or hash table. When using a variable, you can use a reference to it instead of creating a new variable with the same value.

[0166] 5. Process data in segments: Split large-scale data into small blocks for processing, which can reduce the memory required at one time. This method is particularly suitable for processing large files or streaming data, such as the common download function in software. When the machine memory is 8GB, and the data to be downloaded is relatively large, such as 10GB, then the 10GB data cannot be loaded into the buffer at one time when it is downloaded. In this case, the segmentation method can be used for processing: when the memory (RAM) occupied by the downloaded data reaches a certain level (such as 100MB), the 100MB of data can be cut first, divided into a small file and stored in the disk (ROM) first, that is, first written to the disk, and then wait for the second 100MB small file to be written to the disk again and merged with the previous data. And so on. Only 100 splits and merges are needed to complete the download of all data, thus avoiding memory overflow.

[0167] 6. Bitwise operations: In some cases, bitwise operations can be used instead of integer operations, because bitwise operations are operations on binary numbers. At the same time, the CPU can directly operate on binary numbers without creating redundant data structures. There is no need to convert complex data structures into binary, which improves the efficiency of CPU processing and greatly reduces the memory space occupied, thereby achieving the purpose of reducing space complexity.

[0168] 7. Avoid unnecessary copying: For some large object data, such as pictures, videos, audio, etc., unnecessary copying operations should be avoided to reduce the memory space occupied by the data.

[0169] It should be noted that after determining the optimization direction, it is not necessary to optimize to the maximum depth based on the optimization direction. Instead, the time complexity and space complexity can be balanced based on the optimization direction. In addition to the above optimization operations for the optimization direction, general optimization operations can also be set to achieve the optimization of time complexity and space complexity, such as:

[0170] 1. Eliminate unreferenced variables and instructions related to these variables to reduce CPU resource usage:

[0171] Discarding references to irrelevant variables is done to reduce the waste of hardware resources. For example, after a function is called and the return value is assigned to a variable, but this variable is not used in subsequent execution, there is no need to create a variable to store the calculation result, nor to call the function associated with this variable. This not only reduces function calls but also reduces storage space usage, which means that the time and space complexity of the algorithm are reduced.

[0172] 2. Optimize variable declarations (definitions) according to the principle of minimum variable scope; that is, prioritize variables in the following order: local variables, member variables, and global variables to reduce memory usage; that is, when local variables can solve a problem, try to use local variables, otherwise use member variables; similarly, when member variables can solve a problem, try to use member variables, otherwise use global variables. This design is mainly due to the different storage methods, life cycles, and memory usage of the three, which will affect program performance, readability, complexity and other indicators; specifically:

[0173] A. Scope limitation: The scope of a local variable is limited to a specific code block or function, which makes the variable's life cycle relatively short. This can prevent the variable from being accessed where it should not be accessed, thereby improving the maintainability of the code;

[0174] B. Reduce naming conflicts: Using local variables can avoid conflicts with global variables or member variables of the same name. This can improve code clarity, avoid confusion, and enhance readability.

[0175] C. Memory usage: Local variables exist only during the execution of the code block or function in which they are located. When the code block or function is executed, the local variable is automatically released, which means that the memory resources occupied by the variable are also released. In contrast, member variables and global variables have a longer life cycle and may occupy more memory;

[0176] D. Prevent accidental modification: Local variables are only valid within a specific code block, which reduces accidental modification or unnecessary access to the variable. Member variables and global variables have wider accessibility and are more easily accidentally modified in different parts of the program, which means they are less secure than local variables.

[0177] E. Improve code readability and maintainability: Using local variables can make code more independent, reduce code coupling, and improve code readability and maintainability. At the same time, it can be easier to understand and debug the code.

[0178] F. Improved performance: Because local variables have a short lifecycle, the associated memory space is quickly released when a function completes execution. In contrast, the memory of member variables and global variables may persist. If a member variable or global variable references data from a large object, a large amount of memory will be occupied for a long time, resulting in low memory resource utilization and increasing the burden on the garbage collector.

[0179] In general, using local variables can improve code clarity, maintainability, and performance; while member variables and global variables also have applicable scenarios, their abuse should be avoided as much as possible to ensure the robustness and maintainability of the code.

[0180] 3. Execute the plan analysis command to obtain the execution plan and overhead cost of the SQL instruction. Determine the specific optimization direction of the SQL statement based on the execution plan, and then use the SQL optimization engine to complete the optimization processing of the SQL instruction.

[0181] When optimizing code from both time and space perspectives, focus on optimizing time complexity when time is critical, and optimize space complexity when space is critical. Regardless of the optimization strategy used, the ultimate optimization principle is to achieve the same functionality in the shortest execution time while using the least memory. In other words, optimize both time and space complexity.

[0182] Furthermore, after step S20, the method further includes the steps of:

[0183] Step S50, determining whether the source grammar framework contains the grammar body corresponding to the database processing;

[0184] Step S60: If the source grammar framework does not include the grammar body corresponding to the database processing, then exit the conversion operation on the source code.

[0185] If the source grammar framework includes the grammar body corresponding to the database processing, the subsequent steps are executed.

[0186] The code conversion method in this embodiment is applied to a database system. When developing a database system, some code may not involve database processing, including but not limited to DCL (Data Control Language), DQL (Data Query Language), and DML (Data Manipulation Language). Code not involved in database processing does not have the conditions or requirements for conversion. Therefore, to improve code conversion efficiency, code not involved in database processing is not converted.

[0187] It can be understood that the grammatical body represents the specific code execution logic. Therefore, it is possible to determine whether the corresponding code involves database processing through the grammatical body.

[0188] It should be noted that, for a complete source code, as long as it contains codes related to database processing, the source code will be converted.

[0189] Furthermore, after step S40, the method further includes the steps of:

[0190] Step S70, testing the target code and determining whether the test result indicates that the target code has an abnormality;

[0191] Step S80: If the test result indicates that the target code has an abnormality, the abnormal code in the target code is modified according to the abnormality information.

[0192] If the test result indicates that the target code is normal, the code conversion is completed.

[0193] After obtaining the target code, it is tested to ensure its correctness, integrity, security, and usability. The specific code testing method can be set based on actual needs. When an anomaly is detected in the target code, the anomaly is handled. In actual applications, the anomaly can be marked to facilitate developer processing. Alternatively, the anomaly code can be modified based on a preset handling method corresponding to the anomaly type. After the modification, the target code is tested again until the target code is normal, and the code conversion is complete.

[0194] Specifically, code exceptions may include but are not limited to: control exceptions, data type mismatch, exceeding the declared size of a variable, and subscript out of bounds;

[0195] For null value exceptions, you can use conditional checks (such as if statements or ternary expressions) to ensure that the variable is not null before performing operations; or use Assert assertions to clarify which values ​​may be null;

[0196] For data type mismatches, you can use type checking and conversion to ensure that the input parameter type always meets the function's expectations;

[0197] For data that exceeds the declared size of the variable, you can set the declared variable to accommodate the required amount of data to avoid using too small a data type to store data;

[0198] For subscript out-of-bounds errors, mainly for arrays, lists and other types, it is necessary to ensure that the index is used within the legal range and check the variable length before referencing it.

[0199] In general, exception handling needs to ensure that the program can run normally or give clear error prompts under abnormal circumstances, while trying to avoid program crashes.

[0200] This embodiment can ensure the quality of the output target code.

[0201] It should be noted that for the aforementioned method embodiments, for the sake of simplicity, they are all expressed as a series of action combinations, but those skilled in the art should be aware that this application is not limited by the order of the actions described, because according to this application, certain steps can be performed in other orders or simultaneously. Secondly, those skilled in the art should also be aware that the embodiments described in the specification are all preferred embodiments, and the actions and modules involved are not necessarily required by this application.

[0202] Through the description of the above embodiments, those skilled in the art can clearly understand that the methods according to the above embodiments can be implemented by means of software plus the necessary general hardware platform. Of course, they can also be implemented by hardware, but in many cases the former is a better implementation method. Based on this understanding, the technical solution of the present application, or the part that contributes to the existing technology, can be embodied in the form of a software product. The computer software product is stored in a storage medium (such as ROM / RAM, magnetic disk, optical disk), and includes a number of instructions for enabling a terminal device (which can be a mobile phone, computer, server, or network device, etc.) to execute the methods described in each embodiment of the present application.

[0203] The present application also provides a code conversion device for implementing the above-mentioned code conversion method, the code conversion device comprising:

[0204] A first acquisition module is used to acquire source code and match source keywords in the source code;

[0205] A first construction module is configured to construct a source grammar framework corresponding to the source code according to the source keyword, and determine a grammar body included in the source grammar framework;

[0206] A first matching module is configured to match a target keyword corresponding to the grammatical body in a target keyword library, wherein the target keyword is a keyword corresponding to a target language type;

[0207] The first translation module is configured to translate the code corresponding to the grammatical body in the source code using the target keyword to obtain a target code.

[0208] This code conversion device constructs a source grammar framework through source keywords in the source code, so that the overall code structure of the source code can be determined. At the same time, the execution logic of the source code can be determined based on the grammar body in the source grammar framework, so that the target keywords based on the source grammar framework and the grammar body can accurately translate the source code to obtain the target code, thereby realizing automatic code conversion.

[0209] It should be noted that the first acquisition module in this embodiment can be used to execute step S10 in the embodiment of the present application, the first construction module in this embodiment can be used to execute step S20 in the embodiment of the present application, the first matching module in this embodiment can be used to execute step S30 in the embodiment of the present application, and the first translation module in this embodiment can be used to execute step S40 in the embodiment of the present application.

[0210] Furthermore, the first acquisition module includes:

[0211] A first acquiring unit is configured to acquire the source code and acquire a source grammar standard corresponding to the source language type;

[0212] a first checking unit, configured to perform an anomaly check on the source code according to the source syntax standard to determine whether the source code complies with the source syntax standard;

[0213] The first matching unit is configured to match a source keyword in the source code if the source code meets the source syntax standard.

[0214] Furthermore, the first acquisition module includes:

[0215] A second acquiring unit is configured to acquire the source code and a source keyword library corresponding to the source language type;

[0216] The second matching unit is configured to sequentially match the source keywords contained in the source keyword library in the source code from top to bottom.

[0217] Furthermore, the first building block includes:

[0218] A first positioning unit, configured to position the source keyword from top to bottom;

[0219] The first construction unit is configured to determine a source grammar node based on the association relationship of the source keywords to obtain the source grammar framework.

[0220] Furthermore, the first building block includes:

[0221] A first determining unit, configured to determine an optimization direction for code conversion;

[0222] A first optimization unit, configured to perform an optimization operation on the source grammar framework according to the optimization direction;

[0223] The second determining unit is configured to determine the grammatical body according to the source grammatical framework after the optimization operation.

[0224] Furthermore, the device further comprises:

[0225] A first judging module is configured to judge whether the source grammatical framework contains the grammatical body corresponding to the database processing;

[0226] The first exit module is configured to exit the conversion operation on the source code if the source grammar framework does not include the grammar body corresponding to the database processing.

[0227] Furthermore, the device further comprises:

[0228] A first testing module is used to test the target code and determine whether the test result indicates that the target code has an abnormality;

[0229] The first modification module is configured to modify the abnormal code in the target code according to the abnormal information if the test result indicates that the target code has an abnormality.

[0230] Reference Figure 4 In terms of hardware structure, the electronic device may include components such as a communication module 10, a memory 20, and a processor 30. In the electronic device, the processor 30 is connected to the memory 20 and the communication module 10 respectively. The memory 20 stores a computer program, which is simultaneously executed by the processor 30. When the computer program is executed, the steps of the above-mentioned method embodiment are implemented.

[0231] The communication module 10 can be connected to an external communication device via a network. The communication module 10 can receive requests from the external communication device and can also send requests, instructions and information to the external communication device. The external communication device can be other electronic devices, servers or IoT devices, such as TVs, etc.

[0232] Memory 20 can be used to store software programs and various data. Memory 20 may primarily include a program storage area and a data storage area. The program storage area may store the operating system and at least one application required for a function (such as source code). The data storage area may include a database and may store data or information generated based on system usage. Memory 20 may also include high-speed random access memory and non-volatile memory, such as at least one disk storage device, flash memory device, or other volatile solid-state memory device.

[0233] The processor 30 is the control center of the electronic device. It connects all parts of the electronic device using various interfaces and circuits. By running or executing software programs and / or modules stored in the memory 20 and accessing data stored in the memory 20, it performs various functions of the electronic device and processes data, thereby providing overall monitoring of the electronic device. The processor 30 may include one or more processing units; optionally, the processor 30 may integrate an application processor and a modem processor. The application processor primarily handles the operating system, user interface, and application programs, while the modem processor primarily handles wireless communications. It is understood that the modem processor may not be integrated into the processor 30.

[0234] although Figure 4 Although not shown, the electronic device may further include a circuit control module, which is used to connect to the power supply to ensure the normal operation of other components. Figure 4 The electronic device structure shown in the figure does not constitute a limitation to the electronic device, and may include more or fewer components than shown in the figure, or combine certain components, or arrange the components differently.

[0235] The present invention also provides a computer-readable storage medium on which a computer program is stored. The computer-readable storage medium may be Figure 4 The memory 20 in the electronic device may also be at least one of a ROM (Read-Only Memory) / RAM (Random Access Memory), a magnetic disk, and an optical disk. The computer-readable storage medium includes a number of instructions for enabling a terminal device with a processor (which may be a television, a car, a mobile phone, a computer, a server, a terminal, or a network device, etc.) to execute the methods described in various embodiments of the present invention.

[0236] In the present invention, the terms "first", "second", "third", "fourth" and "fifth" are used for descriptive purposes only and cannot be understood as indicating or implying relative importance. For ordinary technicians in this field, the specific meanings of the above terms in the present invention can be understood according to specific circumstances.

[0237] In the description of this specification, the reference terms "one embodiment", "some embodiments", "example", "specific example", or "some examples" mean that the specific features, structures, materials or characteristics described in conjunction with the embodiment or example are included in at least one embodiment or example of the present invention. In this specification, the schematic representations of the above terms do not necessarily refer to the same embodiment or example. Moreover, the specific features, structures, materials or characteristics described can be combined in any one or more embodiments or examples in a suitable manner. In addition, those skilled in the art can combine and combine different embodiments or examples described in this specification and features of different embodiments or examples without contradiction.

[0238] Although the embodiments of the present invention have been shown and described above, the scope of protection of the present invention is not limited thereto. It should be understood that the above embodiments are exemplary and should not be construed as limiting the present invention. Persons skilled in the art may make changes, modifications, and substitutions to the above embodiments within the scope of the present invention, and such changes, modifications, and substitutions should be included within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be based on the scope of protection of the claims.

Claims

1. A code conversion method, characterized in that: The code conversion method comprises: Obtaining source code and matching source keywords in the source code; Constructing a source grammar framework corresponding to the source code according to the source keyword, and determining a grammar body contained in the source grammar framework, where the grammar body indicates code execution logic and function; Matching a target keyword corresponding to the grammatical body in a target keyword library, wherein the target keyword is a keyword corresponding to the target language type; Translating the code corresponding to the grammatical body in the source code by using the target keyword to obtain a target code; Determining the grammatical body included in the source grammatical framework includes: Determine the optimization direction of code conversion; Performing an optimization operation on the source grammar framework according to the optimization direction; Determining the grammatical body according to the source grammatical framework after the optimization operation; The obtaining of source code and matching source keywords in the source code includes: Obtaining the source code and obtaining a source grammar standard corresponding to the source language type; performing anomaly checking on the source code according to the source syntax standard to determine whether the source code complies with the source syntax standard; If the source code meets the source syntax standard, matching source keywords in the source code; The obtaining of source code and matching source keywords in the source code includes: Obtain the source code and a source keyword library corresponding to the source language type; Matching the source keywords contained in the source keyword library in sequence in the source code from top to bottom; The constructing of the source grammar framework corresponding to the source code according to the source keyword includes: Positioning the source keywords from top to bottom; A source grammar node is determined based on the association relationship of the source keywords to obtain the source grammar framework.

2. The code conversion method according to claim 1, wherein After determining the grammatical body included in the source grammatical framework, the method includes: Determining whether the source grammar framework contains the grammar body corresponding to database processing; If the source grammar framework does not include the grammar body corresponding to the database processing, the conversion operation on the source code is exited.

3. The code conversion method according to claim 1, wherein After obtaining the target code, the method includes: Testing the target code and determining whether the test result indicates that the target code has an anomaly; If the test result indicates that the target code has an abnormality, the abnormal code in the target code is modified according to the abnormality information.

4. A code conversion device, characterized in that The code conversion device comprises: A first acquisition module is used to acquire source code and match source keywords in the source code; A first construction module is configured to construct a source grammar framework corresponding to the source code according to the source keyword, and determine a grammar body contained in the source grammar framework, where the grammar body indicates code execution logic and function; A first matching module is configured to match a target keyword corresponding to the grammatical body in a target keyword library, wherein the target keyword is a keyword corresponding to a target language type; A first translation module is configured to translate the code corresponding to the grammatical body in the source code using the target keyword to obtain a target code; The first building block includes: A first determining unit, configured to determine an optimization direction for code conversion; A first optimization unit, configured to perform an optimization operation on the source grammar framework according to the optimization direction; A second determining unit, configured to determine the grammatical body according to the source grammatical framework after the optimization operation; The first acquisition module includes: A first acquiring unit is configured to acquire the source code and acquire a source grammar standard corresponding to the source language type; a first checking unit, configured to perform an anomaly check on the source code according to the source syntax standard to determine whether the source code complies with the source syntax standard; a first matching unit, configured to match a source keyword in the source code if the source code meets the source syntax standard; The first acquisition module includes: A second acquiring unit is configured to acquire the source code and a source keyword library corresponding to the source language type; A second matching unit is configured to sequentially match the source keywords contained in the source keyword library in the source code from top to bottom; The first building block includes: A first positioning unit, configured to position the source keyword from top to bottom; The first construction unit is configured to determine a source grammar node based on the association relationship of the source keywords to obtain the source grammar framework.

5. An electronic device, characterized in that: The electronic device comprises a memory, a processor and a computer program stored in the memory and executable on the processor, wherein the computer program implements the steps of the code conversion method according to any one of claims 1 to 3 when executed by the processor.

6. A computer-readable storage medium, characterized in that The computer-readable storage medium stores a computer program, which, when executed by a processor, implements the steps of the code conversion method according to any one of claims 1 to 3.

Citation Information

Patent Citations

  • Method and device for converting file format in database, equipment and medium

    CN118069723A

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

    CN118092925A