A method, system, and medium for translation of C to Rust code

By employing multi-task reinforcement learning and dependency-guided iterative optimization, this study addresses the limitations of syntax rule-driven tools and insufficient dependency modeling in C-to-Rust translation, achieving high-quality and reliable Rust code generation and improving the accuracy and consistency of the translation.

CN121209888BActive Publication Date: 2026-03-24HARBIN INSTITUTE OF TECHNOLOGY (SHENZHEN) (INSTITUTE OF SCIENCE AND TECHNOLOGY INNOVATION HARBIN INSTITUTE OF TECHNOLOGY SHENZHEN) +1
View PDF 2 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Patents(China)
Current Assignee / Owner
Filing Date
2025-11-28
Publication Date
2026-03-24

AI Technical Summary

Technical Problem

Existing automated migration tools from C to Rust suffer from limitations such as being driven by syntax rules, insufficient dependency modeling, inadequate correctness guarantees, and a scarcity of high-quality migration data. As a result, the generated Rust code lacks Rust idiomatic abstractions and semantic expressions, making it difficult to guarantee the accuracy, robustness, and consistency of the translation.

Method used

We employ a multi-task reinforcement learning and dependency-guided iterative optimization approach. By building a basic model through multi-task fine-tuning and reinforcement learning, and combining compiler feedback and test cases, we design a differentiated reward function to explicitly model cross-language dependencies. We also ensure the grammatical correctness and functional consistency of the translation through an iterative optimization framework.

Benefits of technology

It significantly improves the automation level and quality of C to Rust code translation, solves the problems of frequent syntax errors and difficulty in guaranteeing semantic consistency in translation results in traditional methods, and improves the reliability and applicability of generated code.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121209888B_ABST
    Figure CN121209888B_ABST
Patent Text Reader

Abstract

The application provides a translation method, system and medium from C to Rust code, and the method comprises the following steps: constructing a powerful base model with code translation, grammar understanding and error repair capabilities based on a multi-task reinforcement alignment grammar tuning training method; and performing multi-round correction translation of the base model to the C language project to Rust code by a guided consistency iterative optimization translation framework to ensure the grammar correctness and functional consistency of the translation. Compared with the prior art, the application improves the automation level and final quality of code translation.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of software engineering technology, and in particular to a method, system, and medium for translating C to Rust code based on multi-task reinforcement learning and dependency-guided iterative optimization. Background Technology

[0002] In system-level software development, memory safety and performance efficiency are always core considerations. Due to the need for fine-grained control over hardware and system resources, the C programming language has long been widely used in the development of system-level software such as operating systems, compilers, and databases. While C provides crucial support for system construction thanks to its high performance and low-level control capabilities, its lack of built-in memory safety mechanisms makes it highly susceptible to memory safety vulnerabilities such as buffer overflows, null pointer dereferences, and data races. These vulnerabilities not only seriously threaten the reliability and security of software but are also one of the main causes of serious system vulnerabilities.

[0003] To address these issues, the Rust language was developed. While maintaining near-C performance, Rust eliminates most memory safety risks at the compilation stage through static type checking and ownership mechanisms, thus balancing performance and security. In recent years, with the gradual maturation of the Rust ecosystem, more and more system software development projects have attempted to migrate C code to Rust to improve code security and maintainability. However, manual migration is not only time-consuming and labor-intensive but also prone to introducing new logical errors, urgently requiring automated C-to-Rust translation tools.

[0004] In existing research, the C2Rust tool has been widely used for automated translation tasks. This tool achieves the conversion from C to Rust through syntax rules and type mapping, largely preserving the original behavior of the program and avoiding large-scale manual rewriting. Meanwhile, the rapid development of large-scale language models (LLMs) has provided new possibilities for code generation and translation. Through large-scale pre-training, LLMs possess certain syntactic and semantic understanding and code generation capabilities, and are increasingly being used for automated C to Rust translation tasks, showing potential in generating code that better conforms to Rust language conventions.

[0005] Despite the progress made by existing automated C to Rust migration tools and LLM methodologies, the following key issues remain:

[0006] 1. Limitations of syntax rule-driven tools: While rule-driven tools like C2Rust can generate compilable Rust code, they often retain a lot of C-style design elements. For example, they may use raw pointers or frequently rely on unsafe blocks. Although this type of code can compile, it lacks the abstraction and semantic expression typical of Rust, requiring developers to invest significant time in migration and refactoring.

[0007] 2. Insufficient Dependency Modeling: Existing LLM methods often struggle to capture fine-grained dependencies across files and functions during translation, such as enumerated imports, type aliases, and inter-module calls. Some methods even directly use the entire file as input context, resulting in excessively long sequences that exceed the model's attention range, thus affecting the accuracy and consistency of the translation.

[0008] 3. Insufficient Correctness Guarantee: Although LLM can generate relatively natural Rust code, significant challenges remain in terms of syntactic correctness and functional consistency. The generated code may contain compilation errors or be logically inconsistent with the original C code, seriously affecting executability and reliability.

[0009] 4. Scarcity of high-quality migration data: High-quality pairwise data for C to Rust is limited, and most existing methods rely on zero-shot or few-shot hints, making it difficult to perform targeted optimization at the task level. This directly limits the applicability and performance of the model in complex repository-level code migration tasks.

[0010] In summary, existing automated C to Rust migration solutions cannot simultaneously balance performance, security, and development efficiency. There is an urgent need for a new approach that combines dependency modeling, multi-task learning, and iterative repair mechanisms to improve the accuracy, robustness, and practical usability of translation. Summary of the Invention

[0011] The main objective of this invention is to provide a method, system, and medium for translating C to Rust code based on multi-task reinforcement learning and dependency-guided iterative optimization, aiming to improve the automation level and final quality of code translation.

[0012] To achieve the above objectives, this invention proposes a method for translating C to Rust code, the method comprising the following steps:

[0013] Step S10: Construct a powerful basic model with code translation, syntax understanding and error correction capabilities based on the training method of multi-task reinforcement alignment syntax optimization.

[0014] Step S20: The guided consistency iterative optimization translation framework performs multiple rounds of corrections on the basic model to ensure the syntactic correctness and functional consistency of the translation from C language project to Rust code.

[0015] A further technical solution of the present invention is that step S10 includes:

[0016] Step S101 combines the three tasks of C to Rust code translation, Rust syntax checking, and Rust program repair for multi-task fine-tuning;

[0017] Step S102: Introduce reinforcement learning based on compiler feedback and test cases to optimize the fine-tuned base model.

[0018] A further technical solution of the present invention is that, in step S101, the C to Rust code translation task is that the model receives a C language program and its context as input, with the goal of generating a semantically equivalent Rust program; the Rust syntax checking task is that the model is responsible for evaluating the syntactic correctness of a given Rust code segment and providing diagnostic information when errors exist; the Rust program repair task is that the model receives Rust code containing syntactic or semantic errors and outputs a corrected version.

[0019] A further technical solution of this invention is that, during model training, each training sample is assigned a task-specific label to guide the model in performing corresponding operations. All tasks share a unified autoregressive language modeling objective function for optimization, and its loss function... The definition is as follows:

[0020] ;

[0021] in, This indicates an input prompt. It is the target output sequence. For the i-th token in the sequence, express All previous token sequences, The parameters represent the model.

[0022] A further technical solution of the present invention is that step S102 includes:

[0023] Step S1021 utilizes a real Rust compiler and test suite as an external environment, using their feedback signals as rewards to guide the model to generate more reliable and robust code.

[0024] A further technical solution of the present invention is that, in step S1021, a group relative strategy optimization algorithm is used to optimize the model strategy. Its objective function as follows:

[0025] ;

[0026] The dominance function Calculated using standardized rewards within the group:

[0027] ;

[0028] In the above formula, Indicates the input status. This represents the Rust code generated by the model. It is a reward signal reflecting code quality; within-group mean and standard deviation The reward is calculated by generating a set of candidate responses for the same prompt and is used to normalize the reward and stabilize the training. Reference strategy in divergence term Originating from the monitoring and fine-tuning phase, These are regularization coefficients used to constrain the updated policy. It will not deviate excessively from the reference strategy.

[0029] A further technical solution of the present invention is to design a reward function. The steps include:

[0030] First, compilation rewards The method used to quantify the syntax correctness of code is as follows:

[0031] ;

[0032] in, This represents the total number of errors reported by the Rust compiler. The reward function incentivizes the model to generate code that compiles successfully.

[0033] Secondly, test execution rewards Evaluate the semantic correctness of the code by running predefined test cases:

[0034] ;

[0035] in, and These represent the number of test cases that passed and the total number of test cases, respectively.

[0036] Ultimately, the total reward for function-level samples It is a weighted sum of the two, but we place more emphasis on functional equivalence, therefore assigning a higher weight to the test reward:

[0037] ;

[0038] For repository-level samples, a structural similarity metric is used to approximate the alignment of functions, and a CodeBLEU reward is introduced. This metric comprehensively measures n-gram matching, syntax tree similarity, and data stream alignment.

[0039] ;

[0040] in, It is the code generated by the model. This is the reference baseline code, and the total reward for the repository-level samples. It consists of a weighted average of compilation rewards and CodeBLEU rewards:

[0041] .

[0042] A further technical solution of the present invention is that step S20 includes:

[0043] Step S201 involves performing a deep analysis on the input C language project to extract fine-grained dependency information and align it with the structure of the target Rust language. Step S201 specifically includes:

[0044] Static program analysis tools are used to analyze the source code of the C project and construct a function-level call graph to gain a macroscopic understanding of the overall structure of the project.

[0045] For each C language function, we conduct an in-depth analysis of its abstract syntax tree and extract its fine-grained set of dependencies, which includes other functions it calls, included header files, referenced global variables, used structures, and macro definitions.

[0046] The target Rust project or related Rust codebase was analyzed in the same in-depth way to extract ten key syntax elements of the Rust language: struct, enum, function, import, const, static, type alias, trait, union, and module, with special notes on the implementation blocks associated with struct, enum, and trait;

[0047] Using a pre-trained cross-language code embedding model, all extracted Rust struct elements are vectorized;

[0048] Step S202: Using the dependency mapping relationship established in step S201, the code translation is completed in an iterative refinement manner.

[0049] To achieve the above objectives, the present invention also proposes a C to Rust code translation system, the C to Rust code translation system comprising a memory, a processor, and a C to Rust code translation program stored on the processor, the C to Rust code translation program being executed by the processor to perform the steps of the method described above.

[0050] To achieve the above objectives, the present invention also proposes a computer-readable storage medium storing a C-to-Rust code translator, which, when run by a processor, performs the steps of the method described above.

[0051] The beneficial effects of the C to Rust code translation method, system, and medium of this invention are:

[0052] 1. This invention proposes a multi-task reinforcement alignment syntax tuning training method that combines code translation, syntax checking, and program repair tasks for multi-task fine-tuning, and introduces reinforcement learning based on compiler feedback and test cases for optimization. This method aims to build a powerful foundational model with simultaneous code translation, syntax understanding, and error correction capabilities, solving the problem of traditional methods that only focus on translation itself while neglecting grammatical correctness and fixability.

[0053] 2. This invention designs a dependency-guided consistency-based iterative optimization translation framework, which includes a cross-language dependency alignment module and a consistency-guided translation optimization module. The former accurately extracts and maps fine-grained dependencies such as function calls and type definitions in a C project through static analysis and code embedding models; the latter, in an iterative loop, uses compiler feedback for compilation verification and leverages the large language model itself for consistency checks, ensuring the syntactic correctness and functional consistency of the generated code through multiple rounds of automatic correction.

[0054] 3. This invention designs a differentiated reward function during the reinforcement learning phase. For function-level samples with test cases, rewards are given based on a combination of compilation success rate and test pass rate; for repository-level samples lacking test cases, rewards are given based on a combination of compilation success rate and structural similarity based on CodeBLEU. This design effectively utilizes the characteristics of different types of training data, comprehensively improving the reliability of model-generated code in situations where high-quality pairwise data is scarce.

[0055] 4. This invention combines advanced model training paradigms with a sophisticated inference optimization framework to form an end-to-end automated, high-fidelity code migration solution. This solution not only addresses the insufficient context awareness of existing LLM methods when handling large projects through explicit dependency modeling, but also overcomes the core deficiency of traditional methods in guaranteeing the correctness of translated code functionality by introducing a verification loop between the compiler and the LLM itself. This significantly improves the success rate and practicality of automated C to Rust migration. Attached Figure Description

[0056] Figure 1 This is a flowchart illustrating a preferred embodiment of the C-to-Rust code translation method of the present invention;

[0057] Figure 2 This is a detailed flowchart of step S10;

[0058] Figure 3 This is a detailed flowchart of step S20.

[0059] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and embodiments. Detailed Implementation

[0060] It should be understood that the specific embodiments described herein are for illustrative purposes only and are not intended to limit the scope of the invention.

[0061] This invention proposes a method for code migration that combines high accuracy and robustness in translating from C to Rust. Current code language models often face problems such as insufficient generalization ability, frequent grammatical errors in translation results, and difficulty in guaranteeing semantic consistency when handling repository-level code translation tasks with complex dependencies and strict grammatical constraints. To solve these technical challenges, this invention designs a comprehensive technical solution comprising two stages: model training and inference optimization. The first stage is a "multi-task reinforcement alignment and syntax tuning" training method, which aims to build a basic model with strong translation, syntax understanding, and code repair capabilities through multi-task fine-tuning and reinforcement learning based on compiler feedback. The second stage is a "dependency-guided consistency iterative optimization" translation framework, which ensures consistency and correctness in repository-level code translation through precise cross-language dependency analysis and multiple rounds of iterative correction during the inference stage.

[0062] like Figure 1 As shown, a preferred embodiment of the present invention's method for translating C to Rust code includes the following steps:

[0063] Step S10: Construct a powerful basic model with code translation, syntax understanding and error correction capabilities based on the training method of multi-task reinforcement alignment syntax optimization.

[0064] Step S20: The guided consistency iterative optimization translation framework performs multiple rounds of corrections on the basic model to ensure the syntactic correctness and functional consistency of the translation from C language project to Rust code.

[0065] In this embodiment, step S10 includes:

[0066] Step S101 combines the three tasks of C to Rust code translation, Rust syntax checking, and Rust program repair for multi-task fine-tuning;

[0067] Step S102: Introduce reinforcement learning based on compiler feedback and test cases to optimize the fine-tuned base model.

[0068] In step S101, the C to Rust code translation task involves the model receiving a C language program and its context as input, with the goal of generating a semantically equivalent Rust program; the Rust syntax checking task involves the model evaluating the syntactic correctness of a given Rust code segment and providing diagnostic information when errors exist; and the Rust program repair task involves the model receiving Rust code containing syntactic or semantic errors and outputting a corrected version.

[0069] In this embodiment, during model training, each training sample is assigned a task-specific label to guide the model in performing corresponding operations. All tasks share a unified autoregressive language modeling objective function for optimization, and its loss function... The definition is as follows:

[0070] ;

[0071] in, This indicates an input prompt. It is the target output sequence. For the i-th token in the sequence, express All previous token sequences, The parameters represent the model.

[0072] Step S102 includes:

[0073] Step S1021 utilizes a real Rust compiler and test suite as an external environment, using their feedback signals as rewards to guide the model to generate more reliable and robust code.

[0074] In step S1021, a group relative strategy optimization algorithm is used to optimize the model strategy. Its objective function as follows:

[0075] ;

[0076] The dominance function Calculated using standardized rewards within the group:

[0077] ;

[0078] In the above formula, Indicates the input status. This represents the Rust code generated by the model. It is a reward signal reflecting code quality; within-group mean and standard deviation The reward is calculated by generating a set of candidate responses for the same prompt and is used to normalize the reward and stabilize the training. Reference strategy in divergence term Originating from the monitoring and fine-tuning phase, These are regularization coefficients used to constrain the updated policy. It will not deviate excessively from the reference strategy.

[0079] In this embodiment, a reward function is designed. The steps include:

[0080] First, compilation rewards The method used to quantify the syntax correctness of code is as follows:

[0081] ;

[0082] in, This represents the total number of errors reported by the Rust compiler. The reward function incentivizes the model to generate code that compiles successfully.

[0083] Secondly, test execution rewards Evaluate the semantic correctness of the code by running predefined test cases:

[0084] ;

[0085] in, and These represent the number of test cases that passed and the total number of test cases, respectively.

[0086] Ultimately, the total reward for function-level samples It is a weighted sum of the two, but we place more emphasis on functional equivalence, therefore assigning a higher weight to the test reward:

[0087] ;

[0088] For repository-level samples, a structural similarity metric is used to approximate the alignment of functions, and a CodeBLEU reward is introduced. This metric comprehensively measures n-gram matching, syntax tree similarity, and data stream alignment.

[0089] ;

[0090] in, It is the code generated by the model. This is the reference baseline code. Total reward for repository-level samples. It consists of a weighted average of compilation rewards and CodeBLEU rewards:

[0091] .

[0092] In this embodiment, step S20 includes:

[0093] Step S201 involves performing a deep analysis on the input C language project to extract fine-grained dependency information and align it with the structure of the target Rust language. Step S201 specifically includes:

[0094] Static program analysis tools are used to analyze the source code of the C project and construct a function-level call graph to gain a macroscopic understanding of the overall structure of the project.

[0095] For each C language function, we conduct an in-depth analysis of its abstract syntax tree and extract its fine-grained set of dependencies, which includes other functions it calls, included header files, referenced global variables, used structures, and macro definitions.

[0096] The target Rust project or related Rust codebase was analyzed in the same in-depth way to extract ten key syntax elements of the Rust language: struct, enum, function, import, const, static, type alias, trait, union, and module, with special notes on the implementation blocks associated with struct, enum, and trait;

[0097] Using a pre-trained cross-language code embedding model, all extracted Rust struct elements are vectorized;

[0098] Step S202: Using the dependency mapping relationship established in step S201, the code translation is completed in an iterative refinement manner.

[0099] The following provides a more detailed description of the translation of the C to Rust code in this invention.

[0100] (I) Multi-task reinforcement alignment syntax optimization training method

[0101] To fundamentally enhance the core capabilities of large language models in C to Rust code translation tasks, this invention first proposes an innovative two-stage training method: multi-task reinforcement alignment grammar tuning. This method aims to enable the model not only to learn how to translate code, but also to deeply understand the grammatical rules of the target language (Rust) and possess the ability to proactively correct errors, thereby laying a solid foundation for generating high-quality, executable code.

[0102] The first stage of this training method is multi-task fine-tuning. We deconstruct the C-to-Rust translation process into a multi-task learning problem, requiring the model to simultaneously master three closely related tasks. The specific tasks are defined as follows: 1) C-to-Rust Translation Task ([Task: C2RustTranslation]): The model receives a C program and its context as input, aiming to generate a semantically equivalent Rust program; 2) Rust Syntax Check Task ([Task: SyntaxCheck]): The model is responsible for evaluating the syntactic correctness of a given Rust code segment and providing diagnostic information when errors exist; 3) Rust Program Fix Task ([Task: RustFix]): The model receives Rust code containing syntactic or semantic errors and outputs a corrected version. During training, each training sample is prefixed with a task-specific tag (TaskTag) to guide the model in performing the corresponding operation. All tasks share a unified autoregressive language modeling objective function for optimization, and its loss function... The definition is as follows:

[0103] .

[0104] in, This indicates an input prompt. It is the target output sequence. For the i-th token in the sequence, express All previous token sequences, These represent the model's parameters. To ensure balanced learning across different tasks, we employ a dynamic sampling strategy, dynamically adjusting the proportion of each task in the training batch based on its learning progress. This allows the model to collaboratively improve its three core capabilities: code translation, syntax awareness, and automatic code correction.

[0105] The second stage of this training method involves reinforcement learning based on compiler feedback. While multi-task fine-tuning enhances the model's fundamental capabilities, traditional maximum likelihood estimation objective functions primarily focus on token-level prediction accuracy, making it difficult to guarantee the syntactic compilability and functional correctness of the generated code from a macroscopic perspective. Therefore, this invention introduces a reinforcement learning stage, utilizing a real Rust compiler and test suite as the external environment and their feedback signals as rewards, thereby guiding the model to generate more reliable and robust code. We employ the Group Relative Policy Optimization (GRPO) algorithm to optimize the model policy. Its objective function as follows:

[0106] .

[0107] The dominance function Calculated using standardized rewards within the group:

[0108] .

[0109] In the above formula, Indicates the input status (i.e., prompts for the code translation task). This represents the Rust code (i.e., actions) generated by the model. This is a reward signal reflecting code quality. Within-group mean. and standard deviation The reward is calculated by generating a set of candidate responses for the same prompt and used to normalize and stabilize the training. Reference strategy in divergence term Originating from the monitoring and fine-tuning phase, These are regularization coefficients used to constrain the updated policy. It will not deviate excessively from the reference strategy.

[0110] reward function The design is crucial in this phase; we designed differentiated reward mechanisms for different types of training samples. For function-level samples, since they are usually equipped with test cases, we can perform execution-based verification. Therefore, the reward function combines code compilability and functional correctness. First, compilation reward... The method used to quantify the syntax correctness of code is as follows:

[0111] .

[0112] in, This represents the total number of errors reported by the Rust compiler. The reward function incentivizes the model to generate code that compiles successfully. Secondly, test execution rewards... Evaluate the semantic correctness of the code by running predefined test cases:

[0113] .

[0114] in, and These represent the number of passed test cases and the total number of test cases, respectively. Finally, the total reward for function-level samples. It is a weighted sum of the two, but we place more emphasis on functional equivalence, therefore assigning a higher weight to the test reward: .

[0115] For repository-level samples, due to the lack of readily available test cases, we instead rely on structural similarity metrics to approximate the alignment of functions. (Compilation bonus) The calculation method remains unchanged. To evaluate the semantic similarity between the generated code and the reference code, we introduce the CodeBLEU reward. This metric comprehensively measures n-gram matching, syntax tree similarity, and data stream alignment.

[0116] .

[0117] in, It is the code generated by the model. This is the reference baseline code. Total reward for repository-level samples. It consists of a weighted average of compilation rewards and CodeBLEU rewards:

[0118] .

[0119] By combining the above-mentioned multi-task and reinforcement learning training method, this invention obtains a basic model that performs well in code translation, understanding and repair, which we name MFT-RLTrans.

[0120] Dependency-guided consistency iterative optimization translation framework

[0121] Having established a robust foundational model, this invention further proposes a translation framework called DepTrans to address the complex real-world problem of translating repository-level code. The core idea of ​​this framework is to explicitly model and leverage cross-language dependencies during the translation process, and to progressively refine the translation results through an iterative optimization process that combines compiler feedback and consistency checks, until the translation meets both syntactic and semantic correctness requirements.

[0122] This framework mainly consists of two core modules: a cross-language dependency alignment module and a consistency-guided translation optimization module.

[0123] First, the cross-language dependency alignment module is responsible for performing in-depth analysis of the input C language project before translation to extract fine-grained dependency information and align it with the structure of the target Rust language. The specific steps are as follows: First, using static program analysis tools (such as Tree-Sitter), the source code of the C project is parsed to construct a function-level call graph to grasp the overall structure of the project. Second, for each C language function, its abstract syntax tree is analyzed in depth to extract its fine-grained dependency set, which includes other functions it calls, included header files, referenced global variables, used structs, and macro definitions. Third, the target Rust project or related Rust codebase is analyzed in the same in-depth way to extract ten key Rust syntax elements: struct, enum, function, import, const, static, type alias, trait, union, and module, with special notes on the implementation blocks associated with struct, enum, and trait. Fourth, using a pre-trained cross-language code embedding model (such as BGE-M3), all extracted Rust structural elements are vectorized. For each dependency of every C function, we encode it in the same way and retrieve the top-K semantically closest Rust elements from the Rust struct pool by calculating cosine similarity, thus establishing a mapping relationship from C dependencies to Rust structs. This process ensures that subsequent translations obtain accurate and complete cross-language context information, providing a guarantee for generating code that conforms to the Rust ecosystem and project specifications.

[0124] Secondly, the consistency-guided translation optimization module utilizes the dependency mapping relationships established by the previous module to complete the code translation in an iterative refinement manner. Its workflow is as follows:

[0125] Topology sorting and context construction: C functions are translated one by one according to the topological order of the function call graph. Before translating each function, a context-aware hint is constructed. This hint includes a summary of the C function (a Rust-style docstring pre-generated by LLM), the source code of the C function itself, and pre-processed, aligned Rust dependencies. For excessively long functions in the dependencies (e.g., exceeding 2048 tokens), they are abstracted into their function signatures and functional descriptions to avoid overly verbose hints.

[0126] Initial translation generation: The constructed prompts are input into the MFT-RLTrans model trained in the first stage to generate an initial translated version of Rust code.

[0127] Iterative Repair Loop: Since the initial translation may have grammatical or semantic problems, this invention designs a multi-round repair mechanism.

[0128] Compilation and Verification: First, the Rust compiler is invoked to compile the generated code. If compilation fails, the compiler's error message, along with the original C code, the currently generated Rust code, and the dependency context, is provided back to the model to guide its repair. This process is repeated until the code compiles successfully or the preset maximum number of iterations is reached.

[0129] Consistency Check: After the code compiles, we initiate the consistency check process. This process calls the large language model again, but this time it acts as a "code reviewer," comparing the original C functions and the compiled Rust functions to determine if they are functionally equivalent. If the model identifies functional differences (e.g., inconsistent algorithmic logic, different boundary condition handling, etc.), it outputs a difference analysis report.

[0130] Consistency-based feedback-driven re-fixing: Based on the feedback from the consistency check, the system guides the model to perform a new round of iterative fixes, aiming to eliminate the discovered functional deviations. The fixed code will then re-enter the compilation, verification, and consistency check stages, forming a complete closed loop.

[0131] Final output: The iterative process terminates once the generated code passes both syntactic compilation verification and semantic consistency checks. Finally, the system performs a final compilation to ensure robust integration of all modules, resulting in high-quality, functionally equivalent, and directly integrateable Rust code.

[0132] Through the above methods, this invention not only trains a powerful basic model for code translation, but also designs a sophisticated and automated translation and verification process that can effectively handle complex repository-level code migration tasks, significantly improving the automation level and final quality of code translation.

[0133] The beneficial effects of the C to Rust code translation method of this invention are:

[0134] 1. This invention proposes a multi-task reinforcement alignment syntax tuning training method that combines code translation, syntax checking, and program repair tasks for multi-task fine-tuning, and introduces reinforcement learning based on compiler feedback and test cases for optimization. This method aims to build a powerful foundational model with simultaneous code translation, syntax understanding, and error correction capabilities, solving the problem of traditional methods that only focus on translation itself while neglecting grammatical correctness and fixability.

[0135] 2. This invention designs a dependency-guided consistency-based iterative optimization translation framework, which includes a cross-language dependency alignment module and a consistency-guided translation optimization module. The former accurately extracts and maps fine-grained dependencies such as function calls and type definitions in a C project through static analysis and code embedding models; the latter, in an iterative loop, uses compiler feedback for compilation verification and leverages the large language model itself for consistency checks, ensuring the syntactic correctness and functional consistency of the generated code through multiple rounds of automatic correction.

[0136] 3. This invention designs a differentiated reward function during the reinforcement learning phase. For function-level samples with test cases, rewards are given based on a combination of compilation success rate and test pass rate; for repository-level samples lacking test cases, rewards are given based on a combination of compilation success rate and structural similarity based on CodeBLEU. This design effectively utilizes the characteristics of different types of training data, comprehensively improving the reliability of model-generated code in situations where high-quality pairwise data is scarce.

[0137] 4. This invention combines advanced model training paradigms with a sophisticated inference optimization framework to form an end-to-end automated, high-fidelity code migration solution. This solution not only addresses the insufficient context awareness of existing LLM methods when handling large projects through explicit dependency modeling, but also overcomes the core deficiency of traditional methods in guaranteeing the correctness of translated code functionality by introducing a verification loop between the compiler and the LLM itself. This significantly improves the success rate and practicality of automated C to Rust migration.

[0138] To achieve the above objectives, the present invention also proposes a C to Rust code translation system, which includes a memory, a processor, and a C to Rust code translation program stored on the processor. The C to Rust code translation program is executed by the processor to perform the steps of the method described above, which will not be repeated here.

[0139] To achieve the above objectives, the present invention also proposes a computer-readable storage medium storing a C-to-Rust code translator, which, when run by a processor, performs the steps of the method described above, which will not be repeated here.

[0140] The above description is only a preferred embodiment of the present invention and does not limit the scope of the invention. Any equivalent structural or procedural changes made based on the description and drawings of the present invention, or direct or indirect applications in other related technical fields, are similarly included within the scope of protection of the present invention.

Claims

1. A method for translating C to Rust code, characterized in that, The method includes the following steps: Step S10: Construct a basic model with code translation, syntax understanding and error correction capabilities based on a training method that uses multi-task reinforcement alignment syntax tuning. Step S20: The guided consistency iterative optimization translation framework performs multiple rounds of corrections on the basic model to ensure the syntactic correctness and functional consistency of the translation from C language project to Rust code; Step S10 includes: Step S101 combines the three tasks of C to Rust code translation, Rust syntax checking, and Rust program repair for multi-task fine-tuning; Step S102: Introduce reinforcement learning based on compiler feedback and test cases to optimize the fine-tuned base model; In step S101, the C to Rust code translation task involves the model receiving a C language program and its context as input, with the goal of generating a semantically equivalent Rust program; the Rust syntax checking task involves the model evaluating the syntactic correctness of a given Rust code segment and providing diagnostic information when errors exist; and the Rust program repair task involves the model receiving Rust code containing syntactic or semantic errors and outputting a corrected version. During model training, each training sample is assigned a task-specific label to guide the model in performing corresponding operations. All tasks share a unified autoregressive language modeling objective function for optimization, and its loss function... The definition is as follows: ; in, This indicates an input prompt. It is the target output sequence. For the i-th token in the sequence, express All previous token sequences, The parameters represent the model.

2. The C to Rust code translation method according to claim 1, characterized in that, Step S102 includes: Step S1021 utilizes a real Rust compiler and test suite as an external environment, using their feedback signals as rewards to guide the model to generate more reliable and robust code.

3. The C to Rust code translation method according to claim 2, characterized in that, In step S1021, a group relative strategy optimization algorithm is used to optimize the model strategy. Its objective function as follows: ; The dominance function Calculated using standardized rewards within the group: ; In the objective function and dominance function In the formula, Indicates the input status. This represents the Rust code generated by the model. It is a reward signal reflecting code quality; within-group mean and standard deviation The reward is calculated by generating a set of candidate responses for the same prompt and is used to normalize the reward and stabilize the training. Reference strategy in divergence term Originating from the monitoring and fine-tuning phase, These are regularization coefficients used to constrain the updated policy. It will not deviate excessively from the reference strategy.

4. The C to Rust code translation method according to claim 3, characterized in that, Design reward function The steps include: First, compilation rewards The method used to quantify the syntax correctness of code is as follows: ; in, This represents the total number of errors reported by the Rust compiler; the reward function incentivizes the model to generate code that can be successfully compiled. Secondly, test execution rewards Evaluate the semantic correctness of the code by running predefined test cases: ; in, and These represent the number of test cases that passed and the total number of test cases, respectively. Ultimately, the total reward for function-level samples It is a weighted sum of the two, and to place greater emphasis on functional equivalence, the test reward is given a higher weight: ; For repository-level samples, a structural similarity metric is used to approximate the alignment of functions, and a CodeBLEU reward is introduced. This metric comprehensively measures n-gram matching, syntax tree similarity, and data stream alignment. ; in, It is the code generated by the model. This is the reference baseline code, and the total reward for the repository-level samples. It consists of a weighted average of compilation rewards and CodeBLEU rewards: 。 5. The C to Rust code translation method according to claim 4, characterized in that, Step S20 includes: Step S201 involves performing a deep analysis on the input C language project to extract fine-grained dependency information and align it with the structure of the target Rust language. Step S201 specifically includes: Static program analysis tools are used to analyze the source code of the C project and construct a function-level call graph to gain a macroscopic understanding of the overall structure of the project. For each C language function, we conduct an in-depth analysis of its abstract syntax tree and extract its fine-grained set of dependencies, which includes other functions it calls, included header files, referenced global variables, used structures, and macro definitions. The target Rust project or related Rust codebase was analyzed in the same in-depth way to extract ten key syntax elements of the Rust language: struct, enum, function, import, const, static, type alias, trait, union, and module, with special notes on the implementation blocks associated with struct, enum, and trait; Using a pre-trained cross-language code embedding model, all extracted Rust struct elements are vectorized; Step S202: Using the dependency mapping relationship established in step S201, the code translation is completed in an iterative refinement manner.

6. A C to Rust code translation system, characterized in that, The C-to-Rust code translation system includes a memory, a processor, and a C-to-Rust code translator stored in the memory, the C-to-Rust code translator being executed by the processor to perform the steps of the method as described in any one of claims 1 to 5.

7. A computer-readable storage medium, characterized in that, The computer-readable storage medium stores a C-to-Rust code translator, which, when run by a processor, performs the steps of the method as described in any one of claims 1 to 5.

Citation Information

Patent Citations

  • Code annotation generation method and device based on sequence generative adversarial network

    CN115756475A

  • Code review and optimization method driven by large language model

    CN119512556A