A two-stage C to Rust translation method and system based on large model mixed retrieval

By employing a two-stage translation method and a multi-module system, c2rust is used to generate intermediate Rust code, which is then optimized using rule retrieval. Finally, conventional Rust code is generated, solving the problems of semantic correctness and type safety in the C to Rust migration and achieving efficient and verifiable code migration.

CN122111424APending Publication Date: 2026-05-29EAST CHINA NORMAL UNIV

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
EAST CHINA NORMAL UNIV
Filing Date
2026-04-15
Publication Date
2026-05-29

AI Technical Summary

Technical Problem

Existing technologies struggle to achieve automated migration from C code to Rust code while maintaining both semantic correctness and type safety. Furthermore, existing methods suffer from issues such as code generation relying on unsafe blocks, difficulty in guaranteeing semantic equivalence, and high computational costs.

Method used

A two-stage translation approach based on a large language model, static analysis, and hybrid retrieval is adopted. First, compilable intermediate Rust code is generated through c2rust. Then, rule retrieval and matching are combined to generate idiomatic final Rust code. Fine-grained parsing and dependency ranking are used to verify the method, which is combined with a rule base and a large language model to form a verifiable closed loop.

Benefits of technology

It achieves both semantic correctness and type safety during the migration from C to Rust, improves migration efficiency and the quality of generated code, and provides a feasible and verifiable migration solution.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN122111424A_ABST
    Figure CN122111424A_ABST
Patent Text Reader

Abstract

The application discloses a two-stage C to Rust translation method and system based on large model hybrid retrieval, the method comprising: step 1: constructing a rule base and establishing a vector and keyword two-way index, completing C code parsing, entity extraction and context maintenance; step 2: calling a large language model according to a translation unit and combining c2rust reference to generate a compilable intermediate Rust code and perform single entity verification; step 3: performing hybrid retrieval, rule injection and prompt assembly, generating a habitual final Rust code and performing single entity verification; step 4: two stages are respectively merged into a complete project and end-to-end compilation testing is performed, and the result is output after verification. The system comprises a rule data preparation module, a context maintenance module, a code parsing and recognition module, a rule retrieval module, a prompt assembly module and a translation execution verification module. The application realizes verifiable automatic migration, and takes into account semantic consistency and type safety.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of software engineering and programming language translation technology, specifically a two-stage C to Rust translation method and system based on a large language model, static analysis and hybrid retrieval, namely a two-stage C to Rust translation method and system based on a large model and hybrid retrieval. Background Technology

[0002] Currently, many core software systems are implemented in C, but C lacks memory safety mechanisms, making it prone to security vulnerabilities such as buffer overflows, dangling pointers, and memory leaks, posing security risks to critical systems. Rust, through its ownership model and borrow checking mechanism, provides memory safety at compile time and is increasingly widely used in system programming. Therefore, there is a real need to migrate existing C code to Rust. Manual migration is costly and time-consuming, making it difficult to meet the needs of large-scale engineering migrations. Automated or semi-automated migration methods have become a focus of research and practice.

[0003] However, existing migration techniques suffer from the following problems: First, conversion tools based on abstract syntax tree rule mapping only perform syntax-level conversion, generating code that heavily relies on unsafe blocks, which does not conform to Rust's idiomatic syntax and type safety goals. Second, while directly using large language models for code translation can generate syntactically correct Rust code, it is difficult to systematically guarantee semantic equivalence with the source C code, and it lacks a controllable process combined with rule bases and static analysis. Third, equivalence verification methods based on symbolic execution or fuzzing are computationally expensive and difficult to apply to migration and verification scenarios in large-scale projects. Therefore, a verifiable and implementable automatic migration method from C to Rust that balances semantic correctness and type safety remains relatively scarce.

[0004] Among them, the two-stage C to Rust translation method based on a large language model, static analysis, and hybrid retrieval aims to introduce a hybrid retrieval approach combining rule bases, vector retrieval, and keyword retrieval into the automated migration process. First, intermediate translation yields compilable Rust code. Then, in the final translation stage, the retrieved rules are used for standardization and optimization. The generated code is then compiled and tested for verification, thereby improving migration efficiency while ensuring semantic correctness and type safety. This method and its corresponding multi-module system can parse, retrieve rules, assemble prompts, and generate C projects in two stages according to translation units, providing a practical and verifiable technical solution for C to Rust migration.

[0005] Therefore, there is an urgent need for a two-stage C to Rust translation method and system based on a large language model, static analysis, and hybrid retrieval, to achieve automatic migration of C code while ensuring semantic correctness and type safety. Summary of the Invention

[0006] The purpose of this invention is to realize a two-stage translation method and system for C to Rust based on a large language model, static analysis, and hybrid retrieval. By constructing a translation method and multi-module structure system based on a large language model, automated migration from C to Rust is achieved. c2rust is a conversion tool that statically translates C language source code into Rust code, and its translation result can serve as a reference for the large language model to generate intermediate Rust code. The innovations of this invention include: First, a two-stage translation strategy is adopted. In the first stage, c2rust is used to translate C code units to obtain a reference result, and the large language model combines this reference result to generate compilable intermediate Rust code. Rule retrieval is not performed in this stage. In the second stage, the large language model and rule retrieval and matching (RAG) based on hybrid retrieval are used to standardize the intermediate Rust code to generate the final Rust code. Compilability and semantic correspondence are ensured before introducing the rule base, balancing semantic correctness, type safety, and code usability. Second, C... The code is parsed into finer-grained translation units (functions, global variables, structures, enumerations, etc.) and translated sequentially according to dependency topology, supporting engineering-level consistency. Third, the rule base is built using both vector and keyword indexes, the rule index text is enhanced with both semantic and code pattern enhancements, the two-way retrieval results are normalized and weighted, and optional soft reordering based on tag intersection is available, improving rule recall and task relevance. Fourth, entity verification is combined with end-to-end verification after merging the two stages. When the test fails, the execution trajectory is fed back into the large language model for retranslation and correction, forming a verifiable closed loop. Fifth, PROMPT only fills in C code in step 2 without injecting rules, and fills in Rust code between the rules and the current unit in step 3. The two-stage differentiated filling supports the generation quality.

[0007] The specific technical solution for achieving the objective of this invention is as follows: A two-stage C-to-Rust translation method based on large-model hybrid retrieval, the method specifically includes the following steps: Step 1: Import C to Rust conversion rules from rule documents or JSONL format data. After cleaning and format standardization, construct a rule knowledge base. Build a dual-path index for the rule knowledge base using vector and keyword indexes. The rule text written into the index is a retrieval-oriented structured index text, containing semantic descriptions and code pattern summaries extracted from rule examples to simultaneously enhance the recall of semantic retrieval and code-based queries. When the rule file path and content remain unchanged, reuse existing vector indexes based on the rule file content fingerprint to reduce redundant embedding. Perform static analysis on the C source code to extract entity information and dependencies between functions, global variables, structures, and enumerations. Perform topological sorting of entities based on dependencies to obtain a sequence of translation units arranged in dependency order. Maintain translation context and historical translation results for the C project to be translated by file and function, and prune the history when it exceeds a set length. Step 2: Proceed sequentially by translation unit. Rule retrieval is not performed in this stage. The current C code unit and its metadata are incorporated into the translation context. Based on the predefined PROMPT template, only the current C code unit is filled into the C code input field; no rules are injected into the rule reference field. The translation results of the C source code by c2rust or translated dependencies are used as reference information to assemble the large language model input. The large language model, combining the reference information and the current C code unit, generates compilable intermediate Rust code. The generated intermediate Rust code and statistical information are written into the translation context and result directory. Compilation verification and single-entity level testing are performed on the intermediate Rust code generated by each translation unit. The translation unit is an independently translatable entity obtained after static parsing and dependency topology sorting, including at least functions, global variables, structures, and enumerations. c2rust is a method for statically translating C language source code into Rust. The code conversion tool; the metadata includes at least entity type, entity name, file path, and dependent entity identifier; the translated dependency refers to the translated and verified dependent entity code or signature; the statistics include at least model call count, token consumption, and call time. Step 3: Proceed sequentially by translation unit. Using the current code or entity to be translated as the query, employ a hybrid retrieval method combining vector retrieval and keyword retrieval to perform vector similarity retrieval and keyword matching retrieval from the rule base. Normalize and weightedly fuse the two retrieval results, remove duplicates, select the top_k rules, and assign priority labels. Incorporate the current C code unit and its metadata into the translation context. Fill the rule reference position with the priority label and fill the intermediate Rust code of the unit into the C code input position, assembling it into the input of the large language model. Generate idiomatic Rust code from the large language model. Write the generated final Rust code and statistical information into the translation context and results directory. Perform compilation verification and single-entity level testing verification on the final Rust code generated for each translation unit. The translation unit is an independently translatable entity obtained after static parsing and dependency topology sorting, including at least functions, global variables, structures, and enumerations; the reference rules with priority labels are a set of rules obtained after hybrid retrieval, normalization, and weighted fusion and sorted by relevance, wherein the priority is used to indicate the order of rules in the prompt assembly. Step 4: Merge the unit code generated from the intermediate translation and final translation stages into a complete project, and then perform end-to-end compilation and behavioral testing verification. The intermediate translation stage in Step 2, without rule injection, involves the large language model combined with c2rust translation references to generate compilable intermediate Rust code. The final translation stage in Step 3, with priority-labeled reference rules injected, involves the large language model customizing the intermediate Rust code to generate the final Rust code. When tests fail, the execution trajectory can be fed back into the large language model for retranslation and correction. Static checks and statistics can be performed on the merged Rust project. Verified code is merged according to the project structure and output to a specified directory. The execution trajectory includes at least compilation error information, test output logs, and function call path information.

[0008] A two-stage C-to-Rust translation system based on large-model hybrid retrieval, the translation system being used to execute the aforementioned translation method, the system comprising: The system includes a rule data preparation module, a translation context maintenance module, a C code parsing and entity recognition module, a rule retrieval module, a prompt assembly module, and a translation execution and verification module. The rule data preparation module includes a rule base construction unit and an index building unit, which are used to realize rule base construction and dual-path index building, as well as semantic and code pattern enhancement of rule index text and index reuse based on content fingerprint; The translation context maintenance module includes a context construction unit and a dynamic maintenance unit, which are used to maintain and trim the length of translation contexts and historical translation results for each file and function, and to record and connect task inputs and model outputs. The C code parsing and entity recognition module includes a code parsing unit and an entity recognition unit, which are used to realize C source code parsing, entity and dependency extraction, and translation unit sequence output based on dependency topology sorting; The rule retrieval module includes a hybrid retrieval unit and a priority sorting unit, which are used to realize the normalized weighted fusion of vector retrieval and keyword retrieval, the selection of top_k and priority sorting, and the optional soft reordering based on the intersection of tags, and provide reference rules with priority tags to the prompt assembly module. The prompt assembly module includes a PROMPT template design unit and a PROMPT dynamic filling unit, which are used to realize PROMPT template construction and dynamic filling. Based on the task type, the current C code unit or intermediate Rust code is filled into the C code input position, and reference rules with priority labels are filled into the rule reference position. It also supports combining the c2rust translation result or translated dependencies as reference information. The translation execution and verification module includes an intermediate translation unit, a final translation unit, and a verification output unit. It is used to realize two-stage Rust code generation combining intermediate translation and final translation with c2rust, as well as entity-based compilation and single-entity testing verification, end-to-end verification of the complete project, feedback retranslation when tests fail, optional static checking, and result output. Herein, c2rust is a conversion tool for statically transcribing C language source code into Rust code.

[0009] Furthermore, the rule data preparation module specifically includes a rule base construction unit and an index creation unit; The rule base construction unit is used to import C to Rust conversion rules from rule documents or JSONL format data, and build a rule knowledge base after cleaning and format standardization. The index building unit is used to build a dual-path index for the rule knowledge base using vector index and keyword index. The rule text written into the index is structured index text, which includes at least semantic description, concept tags and code pattern summary to enhance semantic retrieval and code-based query recall. When the rule file path and content do not change after content fingerprint comparison, the existing vector index is reused and the keyword index is updated to reduce repeated embedding and database building overhead.

[0010] Furthermore, the translation context maintenance module specifically includes a context construction unit and a dynamic maintenance unit; The context building unit is used to establish a translation context structure for the C project to be translated by file and by function, and to reserve input slots and output slots for each translation unit; The dynamic maintenance unit is used to maintain the current C code unit, the corresponding translated Rust code segment, and the historical translation results during the translation process. When the historical length exceeds a set threshold, the earliest historical record is pruned to ensure that the context window is controllable and supports the continuity of multi-round translation. The historical length is the number of historical records or the total number of historical tokens.

[0011] Furthermore, the C code parsing and entity recognition module specifically includes a code parsing unit and an entity recognition unit; the code parsing unit is used to perform lexical, syntactic, and semantic analysis on the input C code; the entity recognition unit is used to extract entity information of functions, global variables, structures, and enumerations, construct call relationships and dependencies between entities, and perform topological sorting of entities according to dependencies, outputting a sequence of translation units arranged in dependency order; optionally, circularly dependent entities are detected and restricted or grouped; wherein, the translation unit is an entity object that can be translated independently.

[0012] Furthermore, the rule retrieval module specifically includes a hybrid retrieval unit and a priority sorting unit; The hybrid retrieval unit is used to perform vector similarity retrieval on the vector index to obtain a first candidate rule set, and keyword matching retrieval on the keyword index to obtain a second candidate rule set. The scores of the two retrieval results are normalized and then weighted and merged, deduplicated, and re-sorted. Optionally, soft re-sorting is performed on the rules that have intersection with the query tags. The priority sorting unit is used to select the top_k rules based on the fusion score and assign them priority labels as reference rules for the assembly module; wherein, the priority label is used to indicate the order of the rules in the rule reference position.

[0013] Furthermore, the prompt assembly module specifically includes a PROMPT template design unit and a PROMPT dynamic filling unit; The PROMPT template design unit is used to define a PROMPT template that includes a task description, C code input bits, rule reference bits, and output requirements. The C code input bits are used to fill in the current C code unit to be translated or the intermediate Rust code of that unit, and the rule reference bits are used to fill in the retrieved reference rules. The PROMPT dynamic filling unit is used to dynamically fill the C code input bits and rule reference bits according to the translation stage: in the intermediate translation stage, the current C code unit is filled in and the rule reference bits are not filled in with rules; in the final translation stage, the intermediate Rust code of the current unit is filled in and the reference rules with priority labels are filled in; wherein, the output requirements are used to constrain the output format and convention requirements of the generated Rust code.

[0014] Furthermore, the translation execution and verification module specifically includes an intermediate translation unit, a final translation unit, and a verification output unit; The intermediate translation unit is used to translate the C source code using c2rust to obtain a reference translation result. It takes the PROMPT containing the current C code unit and the reference translation result as input, and sequentially calls the large language model to generate compilable intermediate Rust code corresponding to each unit. It also performs compilation verification and single-entity level test verification on the code generated by each translation unit. The final translation unit is used to generate the final Rust code based on the intermediate Rust code, combined with the PROMPT injection reference rules output by the prompt assembly module, by calling the large language model according to the translation unit to perform habituation, and to compile and perform single entity-level testing and verification for each translation unit. The verification output unit is used to merge the unit code produced by the intermediate translation and the final translation into a complete project, and perform end-to-end compilation and behavioral testing on the merged project; when the test fails, the execution trajectory is fed back into the large language model for retranslation and correction; optionally, static checks are performed on the merged Rust project and the results are statistically analyzed, and the verified code is merged according to the project structure and output to a specified directory; wherein, the execution trajectory includes at least compilation error information, test output logs and function call path information.

[0015] Compared with existing technologies, this invention provides a novel solution for C to Rust code migration based on a large language model, balancing semantic correctness and type safety. The translation method streamlines the rule base construction, hybrid retrieval, two-stage generation, and verification process, achieving semantic accuracy and code usability through rule injection. A two-stage translation strategy (the first stage combines c2rust to generate compilable intermediate code without rule retrieval, and the second stage combines RAG to generate usable final code) ensures compilability and semantic correspondence before introducing the rule base. Fine-grained C code parsing and dependency-driven ordering guarantee engineering-level consistency. Rule recall and relevance are improved through semantic and code pattern enhancement of the rule index and normalized weighted fusion of two-way retrieval. A verifiable closed loop is formed by entity verification and the merging of backend-to-end verification and feedback retranslation in case of test failure. The multi-modal system architecture has high scalability, with each module providing technical support for the translation method, improving migration efficiency and generated code quality. Attached Figure Description

[0016] Figure 1 is a flowchart of the two-stage C to Rust translation method of the present invention; Figure 2 is a diagram of the architecture of the C to Rust two-stage translation system of the present invention; Figure 3 is a schematic diagram of the rule data preparation module of the present invention; Figure 4 is a schematic diagram of the translation context maintenance module of the present invention; Figure 5 is a schematic diagram of the C code parsing and entity recognition module of the present invention; Figure 6 is a schematic diagram of the rule retrieval module of the present invention; Figure 7 is a schematic diagram of the assembly module of the present invention; Figure 8 is a schematic diagram of the translation execution and verification module of the present invention; Figure 9 is a schematic diagram of the PROMPT and rule injection format of the present invention (including differential filling in the intermediate translation and final translation stages); Figure 10 is a flowchart illustrating the process of this invention using a single typedef file as an example; Figure 11 is a schematic diagram showing the code form comparison of the same function in steps 2 and 3 under the typedef example of the present invention. Detailed Implementation

[0017] The specific embodiments of the present invention will now be described in detail with reference to the accompanying drawings, but it should be understood that the scope of protection of the present invention is not limited to the specific embodiments. Example

[0018] Referring to Figure 1, this embodiment discloses a two-stage C-to-Rust translation method based on a large-model hybrid retrieval (in this embodiment, the large model is implemented using a large language model). For ease of writing and reading the figures, the method of this invention is divided into four main steps, referred to as steps 1 to 4 in this paper, and sub-steps are numbered S1-1, S1-2, S1-3, S2-1 to S2-5, S3-1 to S3-6, and S4-1 to S4-3 under each main step, corresponding one-to-one with Figure 1 and the following description. Step 1 unfolds into rule base and dual-path index establishment, C source code parsing and translation unit sequence generation, translation context initialization and maintenance strategy (S1-1~S1-3); Step 2 unfolds into the intermediate translation process completed sequentially by translation unit, including task recording, ruleless prompt assembly, model generation of intermediate Rust, output storage, and entity-based verification (S2-1~S2-5), and rule retrieval is not performed in this stage; Step 3 unfolds into the final translation process completed sequentially by translation unit, including hybrid retrieval and priority rules, task recording, rule-injected prompt assembly, model generation of conventional Rust, output storage, and entity-based verification (S3-1~S3-6); Step 4 unfolds into the merging of the two-stage project, end-to-end verification, failure feedback retranslation, and output after optional static checks (S4-1~S4-3). The following provides further examples of feasible configuration parameters, data formats, and module collaboration; those skilled in the art can substitute specific products and values ​​within an equivalent scope.

[0019] Unless otherwise specified, the following terms in the embodiments have the following meanings: "Prompt" (also commonly written as PROMPT in the industry) refers to the input submitted to the large language model in one go, consisting of a task description and placeholder paragraphs. "C Code Input Position" refers to the C code unit filled in step 2 and the intermediate Rust code of that unit filled in step 3; "Rule Reference Position" is empty in step 2 and a priority retrieval rule is filled in step 3. "Rule Card" refers to a structured rule that can be indexed, retrieved, and injected, often containing a title, description, tags, and positive and negative examples. "Translation Unit" refers to a C-side entity that can be independently translated and verified after parsing and dependency sorting, containing at least functions, global variables, structures, and enumerations. "Intermediate Rust Code" and "Idiomization" refer to the transitional source code in step 2 aimed at compilability and symmetry with C semantics, and the rewriting guided by rules to approximate Rust idioms and facilitate static checking, respectively. "Embedding," "Vector Index," "Keyword Index," "Content Fingerprint," "top_k," and "raw_k" refer to, in order: the vector representation of the text; the vector similarity retrieval structure; term matching and term frequency scoring retrieval (such as BM25); verification information obtained from rule paths and content summaries to determine whether to reuse vectors; the upper limit of the number of rules to be written as prompts; and the number of prefetched candidates (usually larger, for truncation after fusion, deduplication, and reordering). "Hybrid Retrieval," "Normalization," and "Soft Reordering" refer to the fusion of dual-path scores, mapping scores to comparable intervals, and fine-tuning by tag intersection after initial ranking. "Execution Trajectory" refers to the diagnostic information such as compilation, linking, test output, and paths summarized when failure occurs; "Single Test Gated" means that if compilation and single tests fail, the code is not available for dependency reference and does not proceed to the next unit. The decrease in the relevance between retrieval and task is called "retrieval drift"; the short checksum of the text or tag list is called "summary hash." Unless otherwise specified, JSONL, token, cargo, crate, scaffolding code, Clippy, FFI, temperature, inverted index, etc., have their usual meanings in this field.

[0020] Operating Environment and Typical Inputs and Outputs. This embodiment can be implemented on general-purpose computing devices, including computers or servers equipped with processors, memory, and external storage; it relies on Rust toolchains (such as Cargo) for compilation and testing, and on the c2rust tool (which statically translates C source code into Rust) to generate reference translations; the large language model is invoked via a network API or local inference service; the rule vector index can be persisted in a local vector database directory (e.g., using an embedded vector library for persistent collection, Chroma being one such implementation), and keyword branches can use in-memory BM25 or equivalent inverted indexes. The input for a single translation task includes the path to the C project to be migrated, a description of test commands for behavioral verification (such as compilation and testing steps configured in JSON), and optional additional compilation parameters; the output includes intermediate and final Rust source code trees organized according to the project directory structure, verification logs for each unit, optional static inspection statistics files, and statistics files (e.g., in JSON format) recording the number of calls, token consumption, and time consumption for auditing and reproduction.

[0021] Step 1: Rules and Input Preparation (Sub-steps S1-1 to S1-3).

[0022] S1-1 Rule Base Construction and Dual-Path Index Establishment: Importing rules from rule documents or JSONL row-oriented data into C to Rust transformation rules. Each rule in this example can be encoded as a "rule card" record, containing at least fields such as title, natural language description, concept tags, negative example code, and positive example code. During the import phase, deduplication, required field validation, level tag normalization (e.g., distinguishing between "must comply" and "recommended to comply"), and character truncation strategies are performed to control the length of individual index texts, preventing excessively long examples from suppressing semantic fields in the vector space. Subsequently, a rule knowledge base is constructed and a dual-path index is established: On the vector index side, the concatenated text for retrieval (consisting of a title, summary description, tag list, and a "code pattern summary" composed of identifiers and keyword patterns extracted from positive and negative examples) is mapped into dense vectors via an embedding model and written to the vector library; on the keyword index side, a lexical retrieval structure (such as BM25) is established for the same batch of rules to enable symbolic queries such as unsafe, CStr, from_ptr, lifecycle, and error handling. When the rule file path and content summary fingerprint remain unchanged, repeated embedding of already-added rule segments can be skipped. Only the changed parts can be incrementally updated, or existing vector sets can be reused and the keyword index refreshed, thereby reducing the maintenance cost of a large-scale rule base. In the embodiment, top_k (the final number of injected rules) is usually an integer between 4 and 10; the total length of the injected rule text can be set to an upper limit (e.g., several thousand characters). If it exceeds this limit, it will be truncated according to priority to ensure that the context of the large language model is controllable.

[0023] S1-2 C Code Parsing, Entity Extraction, and Topological Sorting: Lexical, syntactic, and necessary semantic analysis is performed on the C source code to obtain an abstract syntax tree or equivalent intermediate representation. Translation units are identified, covering at least functions, global variables, structures, and enumerations, and visibility, signatures, type dependencies, and cross-file references are extracted. A directed dependency graph is constructed based on call, type usage, and initialization dependencies, and topological sorting is implemented to ensure that dependent entities enter the translation queue before their dependents. If strongly connected components or cyclic dependencies are detected, optional strategies such as group translation, manually specifying loop-breaking edges, or file-level degradation can be implemented to avoid deadlocked translation order. The parsing results and unit boundaries are written into the subsequent context structure for iteration in steps 2 and 3 in the same sequence.

[0024] S1-3 Translation Context Initialization and Dynamic Maintenance Strategy Settings: Context slots are established for each file and entity within the project. These slots maintain the current C code snippet, the corresponding intermediate and final Rust, completed and verified dependency code or external signature digests, and multi-turn dialogue history for the large language model. History pruning strategy is configured: when the number of historical records or accumulated tokens exceeds a threshold, the earliest record is discarded based on first-in-first-out or relevance, ensuring the single-turn prompt length remains stable within the model's allowable range. Simultaneously, dependency signatures strongly related to the current unit and recent failure feedback are retained to balance coherence and window limitations.

[0025] Step 2: Intermediate translation (executed sequentially by translation unit, without rule retrieval; sub-steps S2-1 to S2-5).

[0026] In this stage, rule retrieval and rule bit filling are disabled in the process to avoid interference between the rule-driven conventional goal and the intermediate goal of "prioritizing compilability and semantic alignment". Optionally, static pointer analysis tools for raw pointers, etc., can be enabled to provide auxiliary prompts for intermediate representations or generated results. This step does not affect the essential characteristic of not performing rule retrieval in this stage.

[0027] S2-1 records the current translation task input: The current C code unit is fully incorporated into the context and written to metadata: entity type (function / global / structure / enumeration, etc.), symbol name, source file relative path, list of dependent entity identifiers and unique keys within the project, so that the same unit can be reproduced in the log and during retries.

[0028] S2-2 constructs the intermediate translation PROMPT: This assembles structured prompts according to a template, filling only the C code input field with the current C code unit, leaving the rule reference field empty. It appends the static translation result of the corresponding C fragment by c2rust as a "machine reference" to the same prompt or auxiliary message, and concatenates the verified upstream dependency Rust code or minimal signature to ensure the model is consistent with the rest of the project in terms of type and calling convention. System messages can have fixed role settings (e.g., expert-level C→Rust translation assistant), and the output section can be requested to return by file path or code block delimiter for automatic disk write-to-disk processing.

[0029] S2-3 generates intermediate Rust code: The large language model is called, and decoding parameters such as temperature can be set to a lower value according to the task to stabilize API usage; the model outputs intermediate Rust with the primary goal of passing cargo compilation and unit testing under the hint constraints, allowing the temporary retention of more conservative `unsafe` or FFI boundaries, which will be tightened under the rule guidance in step 3 habituation stage.

[0030] S2-4 Record Model Output: Write the generated intermediate Rust according to a predetermined directory structure (e.g., distinguish between the "non-common / intermediate results" tree and the statistics directory), and append information such as the token count, call time, and model identifier of this round to the statistics file for cost accounting and regression comparison.

[0031] S2-5 Entity-Based Verification: Compiles for the current unit; runs minimal test cases covering only the behavior of that unit within the test framework (interfacing with Rust test modules generated from scaffolded code). Timeouts and retries are configurable (e.g., automatically retrying within the limit with error messages when compilation or testing fails). Intermediate results are only marked as available for dependency reference and queued for the next unit when the current unit compiles and its unit tests pass.

[0032] Step 3: Final translation (executed sequentially by translation unit, with rule retrieval and injection enabled; sub-steps S3-1 to S3-6).

[0033] S3-1 Hybrid Retrieval Rule: In step 3, the current code or entity to be translated is used as the retrieval query. In this embodiment, the query is specified as the intermediate Rust code (and the short retrieval sentences extracted from it) obtained by the translation unit in step 2 and combined with entity metadata (entity name, type, path, etc.). The intermediate code is first compressed into a short retrieval sentence by rule matching or regular expression extraction (for example, identifying unsafe, raw pointer, CStr / CString, Option / Result and other patterns from the code and concatenating them into keyword phrases), and then combined with the title-level entity description to avoid directly using the entire long code as embedded input, which would cause retrieval drift. Then, the top _k candidates based on similarity are selected from the vector index (raw_k is greater than top_k, for example, several times the top_k with an upper limit), and the top _k candidates based on keyword index are selected. For vector branches, distance is mapped to similarity (e.g., 1 / (1+d) is used for non-negative distance d). The keyword branch scores are normalized within a range, and then linearly fused according to preset weights (in this example, a weighted sum of approximately 0.55 × vector branch and 0.40 × keyword branch can be used; the remaining weights can be normalized or used for other features). After deduplication of the same rule card, the candidates are sorted by fusion score, and the top _k are selected and assigned priority labels in sequence (the smaller the number, the higher the priority). If the query or rule card carries labels, a soft reordering based on label intersection can be performed on the candidate set to improve domain relevance.

[0034] S3-2 records the current translation task input: The current C code unit and its metadata are incorporated back into the translation context (connected with or incrementally updated with the content written in step 2); at the same time, the current unit identifier, the list of retrieved rule entry identifiers or the digest hash, and the intermediate Rust digest that has been verified in step 2 are written into the context to ensure that the final translation round can reproduce "which rules were used".

[0035] S3-3 Constructing the Final Translation PROMPT: Fill the intermediate Rust code into the C code input field (i.e., this field carries the "Rust intermediate draft to be idiomaticized" in the final stage), and fill the complete rule card text with priority markers into the rule reference field; the rule text can retain positive and negative examples and must / recommended levels to make the model rewrite boundaries clear. System messages and output format constraints consistent with step 2 can be retained at the same time.

[0036] S3-4 Generates Idiomatic Rust Code: It calls the large language model, reduces unnecessary unsafety under rule constraints, adopts idiomatic error handling and type encapsulation, and meets the common rule set requirements of static analysis tools (such as Clippy) enabled in the project.

[0037] S3-5 Record model output: Write the final Rust to the "idiomatic / final" result tree and update the statistics file; if the injection length has triggered truncation, the truncation position can be recorded in the log for parameter tuning.

[0038] S3-6 Entity-based verification: symmetrically performs compilation and single-entity testing on the final Rust, similar to S2-5; if it fails, a re-compilation with error stack and test output can be triggered at the unit granularity, while still being subject to the global maximum number of attempts.

[0039] Step 4: Engineering-level merging, end-to-end verification and closed-loop correction (sub-steps S4-1 to S4-3).

[0040] S4-1 The two phases are merged separately: the intermediate Rust of each unit produced in step 2 is spliced ​​into a complete project according to the target crate layout; the final Rust of each unit produced in step 3 is spliced ​​into another complete project; the two sets of routes are consistent with the module division to facilitate comparison of behavioral differences.

[0041] S4-2 End-to-End Verification: Execute compilation and testing commands consistent with the input side convention in the root directory of the merged project; if the target is a dynamic / static library, link the Rust artifacts and run them using the existing C test driver; if it is an executable file, run it directly and compare the exit codes and output. Record the complete build log and test result file paths.

[0042] S4-3 Failure Feedback Retranslation and Result Output: When end-to-end testing fails, collect the execution trace: at least including compiler diagnostics, linking errors, test framework output, failed test case names, and optional call stack or function-level path summaries. This is then structured and written into the next round of large language model hints, requesting revisions to relevant units or merging of boundary code for the failure point. The "Revision-Merge-Retest" process can be cyclically executed before reaching the configured maximum number of retries. Upon successful completion, optional static checks can be performed on the final project, and alarm categories and quantities can be counted. The verified code is then exported to the specified output directory according to the source project directory structure.

[0043] Referring to Figure 2, the two-stage translation system corresponding to this embodiment includes six functional modules, which are in the following pipeline order: rule data preparation module, translation context maintenance module, C code parsing and entity recognition module, rule retrieval module, prompt assembly module, and translation execution and verification module. The correspondence between the six modules and the sub-steps mentioned above can be specified as follows: The rule data preparation module completes the data assets required for S1-1 in the offline or task initialization phase; the C code parsing and entity recognition module and the translation context maintenance module work together to complete S1-2 and S1-3; the translation context maintenance module is also responsible for connecting the records related to "writing task input and model output into the context and result directory" in S2-1, S3-2 and S3-5; on the intermediate translation path, after the context writing is completed in S2-1, the prompt assembly module and the translation execution and verification module pair up to complete S2-2 to S2-5, and the mixed retrieval of the rule retrieval module is not called on this path; on the final translation path, the rule retrieval module executes S3-1, the prompt assembly module executes S3-3, and the translation execution and verification module executes S3-4 and S3-6; the translation execution and verification module is also responsible for the engineering-level merging, end-to-end testing and failure closure of S4-1 to S4-3. Each module can communicate with the shared results directory through shared configurations (model endpoints, paths, thresholds), which facilitates horizontal scaling into worker nodes in a distributed task queue.

[0044] The rule data preparation module constructs the rule base and establishes a dual-path index, enhances the semantics and code patterns of the rule index text, and reuses the index based on content fingerprints, providing a data foundation for rule injection in step 3. The translation context maintenance module maintains and trims the length of translation contexts and historical translation results for each file and function, and is used to record and connect task input and model output. The C code parsing and entity recognition module parses C source code, extracts entities and dependencies, and outputs the translation unit sequence in dependency order based on topological sorting, providing input for two-stage unit-by-unit translation. The rule retrieval module implements normalized weighted fusion based on dual-path retrieval, top_k selection and priority sorting, and optional soft reordering with tags, providing reference rules with priority tags to the prompt assembly module (in this embodiment, rule retrieval is mainly triggered in the final translation stage, and rule retrieval is not performed in the intermediate translation stage). The prompt assembly module constructs and dynamically fills the PROMPT template, filling only the current C code unit into the C code input position and not filling the rule reference position in the intermediate translation stage, and can be combined with c2rust. The translation results or translated dependencies are used as reference information. In the final translation stage, reference rules with priority tags are filled into the rule reference position, and the intermediate Rust code of the current unit is filled into the C code input position. The translation execution and verification module realizes Rust code generation in combination with the intermediate translation and final translation stages of c2rust, as well as entity-based compilation and single-entity test verification, end-to-end verification of the complete project, feedback retranslation when test fails, and optional static checks and result output.

[0045] The specific implementation process of each module in this embodiment is as follows.

[0046] Referring to Figure 3, the rule data preparation module specifically includes a rule base construction unit and an index building unit. The rule base construction unit specifically includes importing rules from rule documents or JSONL format data, cleaning and standardizing the format, and then building a rule knowledge base. In this embodiment, each rule in the JSONL can undergo field validation, deduplication, and normalization to ensure consistent formatting of rule descriptions, C-side examples, and Rust-side recommended syntax. The index building unit specifically includes building a dual-path index for the rule knowledge base using vector indexing and keyword indexing. The rule text written into the index is structured, retrieval-oriented index text, including at least semantic descriptions, concept tags, and code pattern summaries extracted from rule examples. In this embodiment, a vector database such as Chroma can be used to store the embedding vectors of the index text, and an algorithm such as BM25 can be used to build a keyword inverted index for the rule text. When the rule file path and content match the index metadata (such as index_meta.json) in the persistent directory after comparison using content fingerprinting (e.g., SHA256), the existing vector index is reused and the keyword index is updated. During retrieval, vector similarity retrieval and keyword retrieval are performed separately. The results from both paths are normalized, weighted, fused, deduplicated, and the top_k results are selected. The function of this module is to provide a dual-path index and high-recall rule representation for hybrid retrieval, and to reduce the overhead of repeated embedding and database construction through content fingerprint reuse.

[0047] Referring to Figure 4, the translation context maintenance module specifically includes a context construction unit and a dynamic maintenance unit. The context construction unit specifically includes establishing a translation context structure for the C project to be translated by file and by function. In this embodiment, context slots can be allocated to each file, function, or global entity based on the C project directory and the parsed entity list to store the unit's C source code, retrieval rules, intermediate Rust, and final Rust, etc. The dynamic maintenance unit specifically includes maintaining the current C code unit, translated Rust code snippets, and historical translation results during the translation process, and pruning the history when it exceeds a set length. In this embodiment, the maximum number of historical entries can be set to 10-50, or the maximum number of historical tokens can be set to 4096-8192. When this limit is exceeded, the oldest historical item is removed to ensure that the context length input to the large language model is within the model's limits. The history length can be measured by the number of entries or the total number of historical tokens. The function of this module is to maintain consistency between the project-level and unit-level contexts when calling the large language model multiple times by translation unit.

[0048] Referring to Figure 5, the C code parsing and entity recognition module specifically includes a code parsing unit and an entity recognition unit. In this embodiment, the code parsing unit performs lexical, syntactic, and semantic analysis on the input C code; the entity recognition unit extracts entity information from functions, global variables, structures, and enumerations, constructs call relationships and dependencies between entities, and performs topological sorting of entities according to dependencies, outputting a sequence of translation units arranged in dependency order; a parser based on libclang or an existing C language frontend can be used to output the type, name, file and line number of each entity, as well as a list of other entities it depends on, constructs a directed graph according to dependencies and performs topological sorting to obtain the structure order and function order, ensuring that dependent entities are processed before their dependents; optionally, entities with circular dependencies are detected and restricted or grouped; the translation units are independently translatable entity objects. The function of this module is to decompose the C project into independently translatable entities and obtain a translation sequence in dependency order, providing input for sequential translation and mixed retrieval queries, and ensuring project-level consistency.

[0049] Referring to Figure 6, the rule retrieval module specifically includes a hybrid retrieval unit and a priority ranking unit. The hybrid retrieval unit specifically includes a hybrid retrieval method that combines vector retrieval and keyword retrieval, using the current code or entity to be translated as the query. It performs vector similarity retrieval and keyword matching retrieval from the rule base, and normalizes and weights the two retrieval results, performs deduplication, and re-ranks them. In this embodiment, the current unit source code or entity description text can be embedded and its cosine similarity with the rule base vector can be calculated. Simultaneously, identifiers and type names from the unit are used to retrieve results from the keyword index. The scores from both paths are normalized to [0,1] and then weighted (e.g., 0.55 × vector + 0.40 × keyword) to obtain a comprehensive score. When the same rule is hit in both paths, only one result is retained, and the better score is taken. A certain number of candidates are selected from each path, and then deduplication and ranking are performed based on the comprehensive score. Optionally, rules that intersect with the tags in the query are prioritized (soft re-ranking) to improve relevance while ensuring recall. The priority sorting unit specifically includes selecting the top_k rules based on the fused scores and assigning them priority labels. In this embodiment, the top_k rules can be set as needed, for example, from 5 to 20. The rule with the highest score is placed first in the PROMPT rule reference position, and the priority is used to indicate the order in which rules are arranged during prompt assembly. The function of this module is to provide high-quality reference rules arranged by priority labels for prompt assembly through normalized weighted fusion and optional soft label rearrangement.

[0050] Referring to Figure 7, the assembly module specifically includes a PROMPT template design unit and a PROMPT dynamic filling unit. The PROMPT template design unit specifically includes defining a PROMPT template containing a task description, C code input fields, rule reference fields, and output requirements. In this embodiment, the task description can specify translating C code into Rust, maintaining semantic equivalence, and conforming to Rust conventions as much as possible. The C code input fields are placeholders used to fill in the current unit's source code (intermediate translation) or the unit's intermediate Rust code (final translation). The rule reference fields are placeholders used to fill in retrieved rules according to priority from high to low. The output requirements can specify outputting only Rust code and avoiding explanatory text, etc. The PROMPT dynamic filling unit specifically includes dynamically filling the current C code unit (or intermediate Rust code) and the reference rules with priority tags output by the rule retrieval module into the corresponding positions of the PROMPT template to form the input of the large language model. In the intermediate translation stage, the c2rust translation results or translated structures, enumerations, and other dependencies can also be combined as reference information and input into the large language model. Refer to Figures 8 and 9: Figure 8 shows the connection between the translation execution and verification module and the two-stage call; Figure 9 further shows the PROMPT and rule injection format (including the differentiated filling of the intermediate translation and final translation stages and the c2rust reference / dependency context).

[0051] Referring to Figure 8, the translation execution and verification module specifically includes an intermediate translation unit, a final translation unit, and a verification output unit. The intermediate translation unit specifically includes using c2rust to translate the C source code to obtain a reference translation result, using the PROMPT output by the prompt assembly module (without rules in the rule reference field and the C code input field filled with the current C code unit), and combining the reference translation result and translated dependencies as input to the large language model. It then sequentially calls the large language model to generate compilable intermediate Rust code corresponding to each unit, and performs compilation verification and single-entity level testing verification on the code generated by each translation unit. In this embodiment, c2rust translates the entire C source code to obtain reference Rust code, from which structures or function definitions corresponding to the current unit can be extracted for the large language model's reference. The large language model generates the intermediate Rust code for that unit with compilability and semantic correspondence as the main goal. Each unit passes assembly, compilation, and single-entity testing (e.g., C test scaffolding code calling Rust implementation) before proceeding to the next unit. The final translation unit specifically includes, based on the intermediate Rust code, combining the PROMPT output by the prompt assembly module with injected priority-labeled reference rules, calling the large language model again for idiomatic generation of the final Rust code according to the translation unit, and compiling and performing single-entity level testing and verification for each translation unit; in this embodiment, the intermediate Rust code of the unit is filled into the C code input position in PROMPT, and together with the retrieved priority-labeled reference rules, it is used as input to the large language model, and the large language model is called for idiomatic rewriting; optionally, idiomatic version test scaffold code is generated to align non-idiomatic and idiomatic signatures and ensure consistent behavior. The verification output unit specifically includes merging the code from each unit produced by the intermediate translation and the final translation into a complete project. The merged project undergoes end-to-end compilation and behavioral testing (e.g., running the executable via the test command specified by `test_cmd_path`, or compiling the C driver, linking the Rust library, and then running the test). When a test fails, the execution trajectory is fed back into the large language model for retranslation and correction. The execution trajectory includes at least compilation error information, test output logs, and function call path information. Optionally, the merged Rust project is run using Clippy for static analysis and alarm and error type statistics are collected. After passing the test, the code generated by each unit is merged and written to the output directory according to the original C project structure. In this embodiment, feedback retranslation can inject the execution trajectory and error information from test failures into the next round of large language model calls within a set number of retries.The purpose of this module is to form a verifiable closed loop by combining the intermediate translation of c2rust with the translated dependencies, the final translation injected by combining hybrid retrieval rules, the end-to-end verification after entity verification and the two-stage merging, and the feedback retranslation when the test fails. It can also support quality assessment through static inspection and statistics.

[0052] Referring to Figure 9, which is a schematic diagram of the PROMPT and rule injection format of the present invention, the figure distinguishes between two stages: intermediate translation and final translation. Step 2: The task description states that C code will be translated into Rust while maintaining semantic equivalence. The C code input field is filled with the C code unit to be translated, and also includes the c2rust reference or dependency context (the translation result of the C source code by c2rust or translated structures, enumerations, global variables, other function signatures, etc.). No rules are filled in the rule reference field at this stage. The output requirement is to output only Rust code wrapped with specified tags. Step 3: The task description states that non-standard Rust will be translated into standard Rust. The C code input field is filled with the intermediate Rust code of the unit. The rule reference field is filled with the retrieved reference rules in descending order of priority (each rule may contain level, title, description, counterexample, positive example, tag, etc.). The output requirements are the same as above. The two-stage differential filling support large language model first combines the aforementioned c2rust with translated dependencies to generate compilable intermediate code, and then combines the rules injected through hybrid retrieval to generate conventional final code.

[0053] Referring to Figure 10, which is a flowchart illustrating the process of this invention using a single-file example (typedef_sample.c), the inputs are typedef_sample.c and the rule base (input boxes are indicated by dashed lines). The main path from left to right is as follows: parsing and order (topological sorting, example order is Point, calculate_distance, main), rules and hints (rules are retrieved only in the final stage), two-stage generation (by translation unit C → intermediate Rust → final Rust), merging and end-to-end verification (if failure occurs, the execution trajectory is fed back for retranslation), and output Rust project. The dashed line from "merging and end-to-end verification" points back to "two-stage generation," indicating that if verification or merging fails, the execution trajectory will be fed back to the two-stage generation side by unit for retranslation. No text is written on the connecting lines between the boxes in the main path. Note: This is consistent with steps 1-4 in the specific implementation, the overall flow in Figure 1, and the six modules in Figure 2; the code forms of C, intermediate Rust, and final Rust in the same example are shown in Figure 11.

[0054] Referring to Figure 11, Figure 11 is a schematic diagram comparing the code structure of the same function under the typedef example in step 2 (intermediate translation) and step 3 (final translation). From left to right, the three columns are: C-side segment (source file typedef_sample.c), including the calls to sqrt in the function bodies of typedef struct { float x; float y;} Point, typedef Point Vector, and calculate_distance; intermediate Rust segment (step 2, compileable priority), illustrating #[repr(C)], libc::c_float, and calls to external sqrtf in unsafe blocks; final Rust segment (step 3, idiomatic), illustrating safe idiomatic syntax such as #[derive(Copy, Clone, Debug)], f32, and (dx*dx+dy*dy).sqrt(). Figure caption: corresponds to the generation of intermediate Rust in step 2 and the effect of idiomatic syntax under rule guidance in step 3; see Figure 10 for an overview of the project-level steps.

[0055] The above are merely specific implementations of the present invention, but the scope of protection of the present invention is not limited thereto. Any equivalent substitutions or modifications made by those skilled in the art within the scope disclosed in the present invention, based on the technical solution and inventive concept of the present invention, are included within the scope of protection of the present invention.

Claims

1. A two-stage C-to-Rust translation method based on large-model hybrid retrieval, characterized in that, The method specifically includes the following steps: Step 1: Import C to Rust conversion rules from rule documents or JSONL format data. After cleaning and format standardization, construct a rule knowledge base. Build a dual-path index for the rule knowledge base using vector and keyword indexes. The rule text written into the index is a retrieval-oriented structured index text, containing semantic descriptions and code pattern summaries extracted from rule examples to simultaneously enhance the recall of semantic retrieval and code-based queries. When the rule file path and content remain unchanged, reuse existing vector indexes based on the rule file content fingerprint to reduce redundant embedding. Perform static analysis on the C source code to extract entity information and dependencies between functions, global variables, structures, and enumerations. Perform topological sorting of entities based on dependencies to obtain a sequence of translation units arranged in dependency order. Maintain translation context and historical translation results for the C project to be translated by file and function, and prune the history when it exceeds a set length. Step 2: Proceed sequentially by translation unit. Rule retrieval is not performed in this stage. The current C code unit and its metadata are incorporated into the translation context. Based on the predefined PROMPT template, only the current C code unit is filled into the C code input field; no rules are injected into the rule reference field. The translation results of the C source code by c2rust or translated dependencies are used as reference information to assemble the large language model input. The large language model, combining the reference information and the current C code unit, generates compilable intermediate Rust code. The generated intermediate Rust code and statistical information are written into the translation context and result directory. Compilation verification and single-entity level testing are performed on the intermediate Rust code generated by each translation unit. The translation unit is an independently translatable entity obtained after static parsing and dependency topology sorting, including at least functions, global variables, structures, and enumerations. c2rust is a method for statically translating C language source code into Rust. The code conversion tool; the metadata includes at least entity type, entity name, file path, and dependent entity identifier; the translated dependency refers to the translated and verified dependent entity code or signature; the statistics include at least model call count, token consumption, and call time. Step 3: Proceed sequentially by translation unit. Using the current code or entity to be translated as the query, employ a hybrid retrieval method combining vector retrieval and keyword retrieval to perform vector similarity retrieval and keyword matching retrieval from the rule base. Normalize and weightedly fuse the two retrieval results, remove duplicates, select the top_k rules, and assign priority labels. Incorporate the current C code unit and its metadata into the translation context. Fill the rule reference position with the priority label and fill the C code input position with the intermediate Rust code of this unit, assembling it into the large language model input. Generate idiomatic Rust code from the large language model. Write the generated final Rust code and statistical information into the translation context and results directory, and process the final Rust code generated for each translation unit. The code undergoes compilation verification and single-entity level testing verification; wherein, the translation unit is an independently translatable entity obtained after static parsing and dependency topology sorting, including at least functions, global variables, structures and enumerations; the reference rules with priority labels are a set of rules obtained after the hybrid retrieval, normalization and weighted fusion and sorted by relevance, wherein the priority is used to indicate the order of rules in the prompt assembly; Step 4: Merge the unit code generated from the intermediate translation and final translation stages into a complete project, and then perform end-to-end compilation and behavioral testing verification. The intermediate translation stage in Step 2, without rule injection, involves the large language model combined with c2rust translation references to generate compilable intermediate Rust code. The final translation stage in Step 3, with priority-labeled reference rules injected, involves the large language model customizing the intermediate Rust code to generate the final Rust code. When tests fail, the execution trajectory can be fed back into the large language model for retranslation and correction. Static checks and statistics can be performed on the merged Rust project. Verified code is merged according to the project structure and output to a specified directory. The execution trajectory includes at least compilation error information, test output logs, and function call path information.

2. A two-stage C-to-Rust translation system based on large-model hybrid retrieval, characterized in that, The translation system is used to perform the translation method according to claim 1, and the system includes: The system includes a rule data preparation module, a translation context maintenance module, a C code parsing and entity recognition module, a rule retrieval module, a prompt assembly module, and a translation execution and verification module. The rule data preparation module includes a rule base construction unit and an index building unit, which are used to realize rule base construction and dual-path index building, as well as semantic and code pattern enhancement of rule index text and index reuse based on content fingerprint; The translation context maintenance module includes a context construction unit and a dynamic maintenance unit, which are used to maintain and trim the length of translation contexts and historical translation results for each file and function, and to record and connect task inputs and model outputs. The C code parsing and entity recognition module includes a code parsing unit and an entity recognition unit, which are used to realize C source code parsing, entity and dependency extraction, and translation unit sequence output based on dependency topology sorting; The rule retrieval module includes a hybrid retrieval unit and a priority sorting unit, which are used to realize the normalized weighted fusion of vector retrieval and keyword retrieval, the selection of top_k and priority sorting, and the optional soft reordering based on the intersection of tags, and provide reference rules with priority tags to the prompt assembly module. The prompt assembly module includes a PROMPT template design unit and a PROMPT dynamic filling unit, which are used to realize PROMPT template construction and dynamic filling. Based on the task type, the current C code unit or intermediate Rust code is filled into the C code input position, and reference rules with priority labels are filled into the rule reference position. It also supports combining the c2rust translation result or translated dependencies as reference information. The translation execution and verification module includes an intermediate translation unit, a final translation unit, and a verification output unit. It is used to realize two-stage Rust code generation combining intermediate translation and final translation with c2rust, as well as entity-based compilation and single-entity testing verification, end-to-end verification of the complete project, feedback retranslation when tests fail, optional static checking, and result output. Herein, c2rust is a conversion tool for statically transcribing C language source code into Rust code.

3. The two-stage C-to-Rust translation system according to claim 2, characterized in that, The rule data preparation module specifically includes a rule base construction unit and an index creation unit; The rule base construction unit is used to import C to Rust conversion rules from rule documents or JSONL format data, and build a rule knowledge base after cleaning and format standardization. The index building unit is used to build a dual-path index for the rule knowledge base using vector index and keyword index. The rule text written into the index is structured index text, which includes at least semantic description, concept tags and code pattern summary to enhance semantic retrieval and code-based query recall. When the rule file path and content do not change after content fingerprint comparison, the existing vector index is reused and the keyword index is updated to reduce repeated embedding and database building overhead.

4. The two-stage C-to-Rust translation system according to claim 2, characterized in that, The translation context maintenance module specifically includes a context construction unit and a dynamic maintenance unit; The context building unit is used to establish a translation context structure for the C project to be translated by file and by function, and to reserve input slots and output slots for each translation unit; The dynamic maintenance unit is used to maintain the current C code unit, the corresponding translated Rust code segment, and the historical translation results during the translation process. When the historical length exceeds a set threshold, the earliest historical record is pruned to ensure that the context window is controllable and supports the continuity of multi-round translation. The historical length is the number of historical records or the total number of historical tokens.

5. The two-stage C-to-Rust translation system according to claim 2, characterized in that, The C code parsing and entity recognition module specifically includes a code parsing unit and an entity recognition unit. The code parsing unit performs lexical, syntactic, and semantic analysis on the input C code. The entity recognition unit extracts entity information from functions, global variables, structures, and enumerations, constructs call relationships and dependencies between entities, and performs topological sorting of entities based on dependencies, outputting a sequence of translation units arranged in dependency order. Optionally, it detects, restricts, or groups cyclically dependent entities. The translation unit is an entity object that can be translated independently.

6. The two-stage C-to-Rust translation system according to claim 2, characterized in that, The rule retrieval module specifically includes a hybrid retrieval unit and a priority sorting unit; The hybrid retrieval unit is used to perform vector similarity retrieval on the vector index to obtain a first candidate rule set, and keyword matching retrieval on the keyword index to obtain a second candidate rule set. The scores of the two retrieval results are normalized and then weighted and merged, deduplicated, and re-sorted. Optionally, soft reordering can be performed based on rules that intersect with the query tags; The priority sorting unit is used to select the top_k rules based on the fusion score and assign them priority labels as reference rules for the assembly module; wherein, the priority label is used to indicate the order of the rules in the rule reference position.

7. The two-stage C-to-Rust translation system according to claim 2, characterized in that, The prompt assembly module specifically includes a PROMPT template design unit and a PROMPT dynamic filling unit; The PROMPT template design unit is used to define a PROMPT template that includes a task description, C code input bits, rule reference bits, and output requirements. The C code input bits are used to fill in the current C code unit to be translated or the intermediate Rust code of that unit, and the rule reference bits are used to fill in the retrieved reference rules. The PROMPT dynamic filling unit is used to dynamically fill the C code input bits and rule reference bits according to the translation stage: in the intermediate translation stage, the current C code unit is filled in and the rule reference bits are not filled in with rules; in the final translation stage, the intermediate Rust code of the current unit is filled in and the reference rules with priority labels are filled in; wherein, the output requirements are used to constrain the output format and convention requirements of the generated Rust code.

8. The two-stage C-to-Rust translation system according to claim 2, characterized in that, The translation execution and verification module specifically includes an intermediate translation unit, a final translation unit, and a verification output unit. The intermediate translation unit is used to translate the C source code using c2rust to obtain a reference translation result. It takes the PROMPT containing the current C code unit and the reference translation result as input, and sequentially calls the large language model to generate compilable intermediate Rust code corresponding to each unit. It also performs compilation verification and single-entity level test verification on the code generated by each translation unit. The final translation unit is used to generate the final Rust code based on the intermediate Rust code, combined with the PROMPT injection reference rules output by the prompt assembly module, by calling the large language model according to the translation unit to perform habituation, and to compile and perform single entity-level testing and verification for each translation unit. The verification output unit is used to merge the unit code produced by the intermediate translation and the final translation into a complete project, and perform end-to-end compilation and behavioral testing on the merged project. When a test fails, the execution trajectory feedback is injected into the large language model for retranslation and correction. Optionally, static analysis can be performed on the merged Rust project and the results can be statistically analyzed. The verified code can be merged according to the project structure and output to a specified directory. The execution trace includes at least compilation error information, test output logs, and function call path information.