Authors’ overview
Automating C-to-Rust migration is critical for improving software security without sacrificing performance. Traditional rule-based methods struggle with diverse C idioms, often producing rigid and unidiomatic Rust code. Large Language Models (LLMs), trained on massive code corpora, offer a promising alternative by leveraging cross-language generalization to generate more idiomatic and maintainable Rust code. First, existing LLM-based approaches fail to handle cross-file dependencies effectively, either ignoring them or including entire files as context, which limits accurate dependency modeling. Second, complex dependencies and structured inputs and outputs make it difficult to verify syntactic correctness and functional equivalence at the repository level. Third, the lack of large-scale C-Rust parallel data constrains model performance. We propose DepTrans, a framework that combines model capability enhancement with structured inference. DepTrans introduces Reinforcement-Aligned Syntax Training to improve generation quality through multi-task fine-tuning and feedback-driven reinforcement learning. It further applies Dependency-Guided Iterative Refinement to capture fine-grained cross-file dependencies and iteratively refine generated Rust code. We construct a dataset of 85k training samples and a benchmark of 145 repository-level instances. Experiments show that DepTrans achieves a 60.7 percent compilation success rate and 43.5 percent computational accuracy, outperforming the strongest baseline by 22.8 and 17.3 percentage points. It also successfully builds 7 of 15 industrial C projects, demonstrating its practical potential.
Introduction
System-level development demands a rigorous balance between performance and memory safety. While C provides the necessary low-level control, its inherent lack of memory safety remains a primary source of critical vulnerabilities. Rust has emerged as a compelling alternative, offering C-equivalent performance while enforcing memory safety via its static ownership system. Consequently, migrating legacy C codebases to Rust is now a strategic priority for enhancing software security. However, the manual migration process is prohibitively labor-intensive and error-prone, necessitating the development of robust, automated C-to-Rust translation solutions.
In recent years, tools like C2Rust have automated C-to-Rust migration by mapping C syntax to Rust constructs. However, these rule-based methods often produce Rust code that retains C-style design, such as raw pointers and unsafe blocks. Although the output is typically compilable, it is frequently unidiomatic, requiring developers to invest manual efforts in post-translation refactoring. LLMs have recently shown strong performance on code-related tasks. Previous studies have shown that compared to rule-based tools such as C2Rust, LLMs offer clear advantages in producing Rust code that better aligns with the idiomatic practices of the language, significantly reducing the manual refactoring. Despite the effectiveness of LLMs, existing LLM-based approaches also face critical challenges. First, LLMs frequently struggle with the fine-grained dependencies of large-scale repositories, leading to fragmented and inconsistent translations. Simply translating functions in isolation or cramming entire files into the prompt typically yields suboptimal results, as the model fails to maintain a coherent global view across file boundaries, resulting in broken references and inconsistent program logic. Second, the complex dependencies and structured inputs/outputs of repository-level software make it exceptionally difficult to validate syntactic correctness and functional equivalence. The reliance on intricate data structures defined across multiple modules hinders the generation of standalone test cases, thereby depriving the model of the high-quality diagnostic feedback—such as compiler diagnostics or execution traces—essential for driving effective iterative self-refinement. Finally, the scarcity of parallel C-Rust repositories in training corpora hinders models from learning the complex mappings required for cross-file coherence. Without sufficient exposure to diverse repository-level patterns, LLMs frequently generate code with unresolved references or fragmented logic. This lack of architectural awareness leads to significantly degraded compilation success rates and functional accuracy in large-scale migrations.
To address these challenges, we propose DepTrans, a dependency-guided approach for repository-level C-to-Rust translation. The core of DepTrans lies in its synergy between model-level capability enhancement and a structured inference framework. First, we introduce Reinforcement-Aligned Syntax Training (RAST) to bolster the model’s intrinsic dependency awareness and task-specific adaptation. This two-stage scheme employs multi-task fine-tuning to capture distant structural correlations, followed by compiler-feedback reinforcement learning to further enforce syntactic correctness and functional equivalence. By optimizing the model’s fundamental translation and repair capabilities, RAST provides a robust foundation for handling complex repository structures. Second, building upon the enhanced model, we develop a Dependency-Guided Iterative Refinement (DGIR) framework to orchestrate the translation process. This involves a Cross-Language Dependency Alignment strategy that decomposes C projects into manageable units and performs incremental, bottom-up translation following topological orders. By mapping extracted C dependencies to a semantically aligned Rust dependency pool, the framework provides precise, fine-grained context. Furthermore, a Consistency-Guided Refinement strategy iteratively optimizes the translation by integrating compiler diagnostics with LLM-based self-consistency checks, ensuring the output is both syntactically valid and functionally aligned.
Multi-Task Fine-Tuning
While the inference framework provides structural guidance, the model’s intrinsic ability to handle repository-level nuances often remains a bottleneck. LLMs frequently struggle with cross-file structural dependencies and lack a specialized synergy between translation, detection, and repair. To bridge this gap, we formulate the initial training stage as a multi-task learning problem. This approach forces the model to internalize the relationship between C logic and Rust syntax while developing an acute sensitivity to migration pitfalls.
Compiler-Feedback Reinforcement Learning
While multi-task fine-tuning establishes a foundational mapping, the maximum likelihood objective often prioritizes token-level probability over the rigorous, binary requirements of a compiler. To bridge the gap between “plausible” and “executable” code, we introduce a reinforcement learning stage using Group Relative Policy Optimization (GRPO). This stage aligns the model with the strict type system of Rust by treating the compiler and test suite as an interactive environment for policy optimization.
Cross-Language Dependency Alignment
Repository-level translation is hindered by the fragmentation of semantic context across file boundaries. Without explicit dependency modeling, LLMs often generate code that references undefined symbols or violates target-language module structures. To mitigate this, we propose a Cross-Language Dependency Alignment module that bridges the semantic gap between the source C repository and the target Rust environment through three steps.
Consistency-Guided Translation Refinement
Direct LLM translation at the repository level often produces “hallucinated” syntax or logic shifts that violate cross-file invariants. To bridge this gap, we propose a two-stage refinement module designed to maximize the LLM’s self-refinement potential. By providing structured contextual grounding and multi-dimensional feedback, the module empowers the model to iteratively identify and rectify its own translation errors.
Repository-Level Dataset Construction
Phase 2: Hybrid Semantic Alignment. To identify equivalent functions, we employ a three-step filtering process: (1) Coarse Retrieval: We utilize BGE-M3, a widely-used model for cross-lingual code retrieval, to efficiently retrieve top candidates via cosine similarity. (2) Model-based Re-ranking: We leverage Qwen2.5-Coder-32B to perform semantic verification, exploiting its reasoning capabilities to filter out false positives. (3) Manual Audit: The first and second authors conduct a final review of the aligned pairs within the full repository context to resolve any subtle discrepancies and ensure high-fidelity ground truth.
Phase 3: Test-based Coverage Identification. To determine which functions are verifiable via execution, we employ a straightforward function-level deletion strategy. For each Rust function, we temporarily remove its body and execute cargo test. If this leads to a test failure, we interpret it as a definitive signal that the function’s logic is covered by the existing test suite, marking it as a “test-verifiable” sample.
Function-Level Dataset Construction
Phase 2: Compiler-Guided Synthesis. To obtain high-quality C-Rust pairs, we employ an automated translation-and-refinement pipeline. Each C function is initially translated by an LLM, followed by an iterative optimization process guided strictly by Rust compiler diagnostics. This strategy ensures that the ground-truth authority rests on the rigorous compiler rather than the generative model, resulting in syntactically valid and idiomatic Rust counterparts.
Phase 3: Multi-Task Label Generation. Based on the synthesis trajectories, we derive labels for three synergistic tasks: (1) Translation, using successfully compiled C-Rust pairs as ground truth; (2) Detection, using both successful and failed attempts to train the model on error identification; and (3) Repair, using the logs of the refinement process to provide realistic error-correction trajectories for supervised fine-tuning.
Dataset Statistics
Multi-task Fine-tuning Dataset. To equip the model with fundamental translation and self-repair capabilities, we construct three specialized tasks under the function-level category: (1) CodeTrans for C-to-Rust translation, (2) SyntaxCheck for error detection and analysis, and (3) CodeFix for iterative code repair. These tasks, totaling over 82k samples, provide a balanced coverage of syntactic and functional patterns required for cross-language migration.
Reinforcement Learning Dataset. To further align the model with compilation and functional requirements, we utilize a hybrid RL dataset. This includes 2,370 function-level samples (Function) and 310 repository-level samples (Repository). The latter specifically incorporates cross-file dependencies to bolster the model’s ability to navigate architectural constraints during the alignment process.
Evaluation Benchmarks. For a robust assessment of repository-level migration, we establish two benchmarks under the Repository category derived from parallel C/Rust projects. DCBench, sourced from the deltachat-core repository, comprises 125 samples with an average of 316 tokens. Its complex dependencies and 175-file scale provide a highly challenging testbed for contextual reasoning. In contrast, IMCBench, derived from incubator-milagro-crypto, contains 20 samples from a 121-file codebase, serving as an additional setting to evaluate basic dependency handling.
Selected LCMs
We evaluate our framework across two state-of-the-art Large Code Model families. DeepSeek-Coder (DSC) represents a LLaMA-based decoder-only architecture, for which we select the 6.7B and 33B instruction-tuned variants. Qwen2.5-Coder (QWC) provides extensive long-context support (128K tokens), and we utilize its 7B, 14B, and 32B versions. This diverse configuration allows for a comprehensive analysis of how model scale and architectural capabilities influence syntactic validity and semantic fidelity in complex C-to-Rust migration.
Research Questions
To address RQ1, we evaluate both our DGIR and RAST-7B on DCBench and IMCBench, which feature varying degrees of rich, cross-file dependencies ranging from standalone modules to intricate architectures. To answer RQ2, we perform a series of ablation studies, systematically decoupling the DGIR’s components and varying the RAST reward signals to quantify their respective impacts on syntactic and semantic performance. For RQ3, we assess the practical utility of DepTrans on HWBench, a benchmark comprising 15 industrial C projects from Huawei’s database systems. With codebases ranging from 1,000 to 3,000 lines.
Evaluation for RQ3
To evaluate practical effectiveness in real-world scenarios, we compare DepTrans against two project-level strategies: (1) Base, which translates all C files simultaneously following previous work’s setting; and (2) Sactor, a two-stage pipeline combining C2Rust static translation with LLM-based refinement. This comparison demonstrates that DepTrans’s integrated dependency modeling handles complex module relationships more effectively than naive global prompting or rigid multi-stage pipelines.
Performance Metrics
We adopt three metrics: (1) Compilation Success Rate (CSR), the proportion of compilable translations; (2) Computational Accuracy (CA), functional equivalence with reference outputs; and (3) CodeBLEU, structural and lexical similarity to reference Rust code. For HWBench, we report Num Build (projects compiled), since these projects lack Rust test cases.
Effectiveness of DGIR in C-to-Rust Translation
(1)DGIR achieves superior overall performance by effectively resolving repository-level dependencies. On the structurally complex DCBench, DGIR consistently outperforms all baselines across all model sizes. For instance, with Qwen2.5-Coder-32B, DGIR achieves a compilation success rate of 51.2% and a computational accuracy of 36.8%, outperforming the best-performing baseline File Context by 20.8% and 14.4%, respectively. This gap underscores that merely providing file context is insufficient for capturing the global dependency information necessary for repository-level consistency. On IMCBench, while reduced complexity benefits most methods, DGIR remains superior in functional correctness. With Qwen2.5-Coder-14B and 32B, DGIR achieves a computational accuracy of 70.0%, exceeding the best baseline by up to 20%. Even with DSC-6.7B, the computational accuracy improves from 40.0% (File Context) to 65.0% with DGIR. These results underscore that by modeling global project structures and integrating feedback-driven repair, DGIR not only facilitates syntactic correctness but also enhances the preservation of semantic equivalence.
Ablation Study of DGIR
Experimental results confirm that every component of DGIR is indispensable. First, removing structural rewriting (Plain Deps) causes a clear decline in overall accuracy; for instance, the Total CA on QWC-32B drops from 41.4% to 35.9%, indicating that fine-grained structural alignment is fundamental for capturing effective repository context. Second, removing compiler feedback (w/o Compile) directly impacts syntactic validity; specifically, the compilation success rate (CSR) on DCBench with QWC-14B decreases from 44.5% to 34.4%, proving that compiler-driven repair is essential for high compilation rates. Third, excluding semantic consistency checks (w/o Consistency) significantly compromises functional correctness. Notably, the functional accuracy on IMCBench (QWC-32B) drops sharply from 70.0% to 45.0%. Interestingly, this performance decay is negligible on smaller-scale models, suggesting that consistency guidance is more effective for models with stronger reasoning capabilities, whereas it may be considered optional for smaller models with limited self-correction potential. Finally, removing the entire iterative repair loop (w/o Repair) results in the most severe degradation across metrics; for example, the CSR on DCBench (QWC-7B) plummets from 42.4% to 29.6%, validating that the iterative refinement process is the core engine for bridging the gap between initial translation and executable, correct code.
Ablation Study of RAST-7B
A balanced reward configuration is critical for achieving robust translation. Specifically, the Compilation-Only (1:0) strategy causes performance degradation, evidenced by a near-perfect Total CSR (97.9%) but a complete failure in functional correctness (0.0% Total CA), as the model learns to exploit the reward mechanism by generating trivial, safe outputs (e.g., panic!) to satisfy compilation constraints without implementing actual logic. Conversely, exclusively prioritizing or over-emphasizing alignment rewards (Test-Only 0:1 and Test-Heavy 1:2) compromises syntactic reliability; for instance, while the 1:2 variant achieves the highest semantic similarity (Total CodeBLEU 66.5%), it suffers a decline in computational accuracy compared to the balanced setting (40.8% vs. 43.5%). Ultimately, the Balanced (1:1) configuration demonstrates superior robustness, achieving the highest Total CA of 43.5% alongside a competitive compilation rate, confirming that the joint optimization of syntactic validity and functional alignment is requisite for high-fidelity migration.
RQ3: Industrial Project-level Migration
DepTrans demonstrates superior robustness and practical effectiveness in industrial-scale migration. On HWBench, the Base strategy nearly fails across all configurations, while Sactor achieves only modest improvements (e.g., 5 builds on QWC-32B). In contrast, DGIR independently attains superior performance, with 6 and 7 successful builds on QWC-14B and QWC-32B, respectively, even without RAST adaptation. When RAST is integrated, RAST-7B’s successful builds increase from 3 to 7, effectively matching the performance of the much larger QWC-32B model. This underscores both the robustness of our inference framework and the efficiency of our task-specific tuning.
Impact of Repair Iterations in DGIR
Increasing repair iterations improves performance but incurs higher costs. For compiler-guided repair, computational accuracy rises from 31.03% at iteration 1 to a peak of 35.17% at iteration 4, yet this comes with a sharp increase in token consumption exceeding 100k at iteration 5. Similarly, consistency-guided repair shows marginal improvements, where iteration 5 achieves the highest compilation rate of 53.10% but consumes more tokens than iteration 1 which attains identical computational accuracy.
To balance translation performance with inference overhead, we recommend setting the compiler-guided repair iteration count to 2–3 and the consistency repair iteration count to 1 or 3. This configuration maximizes computational efficiency while maintaining robust migration quality in real-world pipelines.
How safe is the Rust code generated by DepTrans?
DepTrans consistently minimizes unsafe code ratios across all benchmarks. For instance, the unsafe code ratio remains below 3% for all models on DCBench and HWBench. Even on the complex CRustBench, the ratio stays remarkably low, exemplified by 3.39% for DSC-6.7B, which confirms the framework’s capability to effectively reduce memory safety risks and ensure maintainability.
Threats To Validity
Potential Data Leakage. Since pretraining data is not public, we cannot fully rule out leakage. However, the poor performance of simple prompting suggests this is not a major issue. The significant gains from our framework confirm that the improvements come from our method rather than the model just memorizing the data.
Related Work
Existing C-to-Rust migration approaches follow two primary paradigms: rule-based and LLM-based. Rule-based approaches, such as C2Rust, leverage compiler infrastructures to ensure structural equivalence, while subsequent works incorporate static analysis and alias emulation to enhance safety. Although these tools provide high functional fidelity, the resulting code is often unidiomatic and fails to fully utilize Rust’s safety guarantees.
LLM-based approaches aim to bridge this gap by learning idiomatic patterns from large-scale corpora. Recent studies have explored direct translation with feedback loops or hybrid refinement strategies that post-process rule-based outputs. These diverse explorations have collectively highlighted two persistent, open challenges in the field: the difficulty of maintaining coherence across complex repository-level dependencies and the scarcity of high-quality parallel data. Our work, DepTrans, specifically addresses these architectural and data-level bottlenecks.
Conclusion
In this paper, We propose a novel approach for repository-level C-to-Rust translation. It consists of two key components: a dependency-guided translation framework and a two-stage training paradigm. The framework extracts fine-grained dependencies from C code, maps them to their Rust equivalents, and constructs precise translation context to guide LLM-based generation. It further applies compiler diagnostics and LLM-based consistency checks for iterative error repair. The training paradigm combines multi-task fine-tuning with compiler-feedback reinforcement learning, supported by our constructed dataset of function-level and repository-level C-Rust pairs. Extensive experiments show that our approach consistently improves compilation success and functional correctness over strong baselines, demonstrating its effectiveness for practical migration scenarios.


