arXivDaily arXiv每日学术速递 周一至周五更新
arXiv周末暂无论文更新,休息一下吧,周末愉快~~
arXiv 2503.17741cs.SE
收藏

RustMap:通过程序分析与大语言模型实现项目级C到Rust迁移

RustMap: Towards Project-Scale C-to-Rust Migration via Program Analysis and LLM

Xuemeng Cai, Jiakun Liu, Xiping Huang, Yijun Yu, Haitao Wu, Chunmiao Li, Bo Wang, Imam Nur Bani Yusuf, Lingxiao Jiang

AI总结:

针对C到Rust迁移中现有工具生成代码不安全、难维护的问题,提出依赖引导结合LLM的RustMap方法,通过分块翻译、测试反馈迭代优化,生成更安全、符合惯用规范的可运行Rust代码,实验效果优于现有工具。

摘要:

将现有C程序迁移到Rust的需求日益增长,因为Rust在保持C语言高性能的同时,还具备更出色的内存安全性。然而,C与Rust之间存在诸多特性差异——例如指针和引用的定义与使用方式截然不同——这带来了远超单纯语法翻译的重大挑战。现有的自动化翻译工具(如C2Rust)可能过度依赖基于模板的语法翻译,生成的不安全Rust代码既难以让人类开发者阅读、维护,甚至可能无法编译。业界迫切需要更具语义感知能力的翻译方案,以生成更安全、符合语言惯用规范且可运行的Rust代码。\n本文提出了一种新颖的、基于依赖引导与大语言模型(LLM)的C到Rust翻译方法RustMap,其核心基于三个关键思路:(1)利用LLM的能力,将给定的小规模C代码片段转换为符合Rust惯用规范的代码;(2)针对LLM处理大型代码库的局限性,根据使用依赖关系将项目级C程序拆分为更小的单元进行翻译,再将这些单元组合成可运行的Rust程序;(3)通过测试用例检查输入输出等价性,在执行状态出现偏差时定位故障代码,并结合编译与测试错误的反馈迭代优化翻译,从而提升翻译后Rust程序的正确性。\n我们使用GPT-4o作为底层LLM,在126个真实世界程序上对RustMap进行了实证评估,其中包括125个来自Rosetta Code的程序,以及一个超过7000行的bzip2实现。RustMap展现出了可观的效果:它引导GPT-4o生成了符合惯用规范、可读性强且功能完整的Rust代码,其不安全代码的占比远低于其他工具,同时还揭示了可复用的重要翻译模式,可供未来研究参考。

英文摘要:

Migrating existing C programs into Rust is increasingly desired, as Rust offers superior memory safety while maintaining C's high performance. However, vastly different features between C and Rust--e.g., distinct definitions and usages of pointers and references--pose significant challenges beyond mere syntactic translation. Existing automated translation tools, such as C2Rust, may rely too much on syntactic, template-based translation and generate unsafe Rust code that is hard for human developers to read, maintain, or even compile. More semantic-aware translation that produces safer, idiomatic, and runnable Rust code is much needed. This paper introduces a novel dependency-guided and large language model (LLM)-based C-to-Rust translation approach, RustMap, based on three key ideas: (1) Utilize LLM capabilities to produce idiomatic Rust code from given small pieces of C code, (2) Mitigate LLM limitations in handling large codebases by breaking project-scale C programs into smaller units for translation according to their usage dependencies and composing them into a runnable Rust program, and (3) Enhance the correctness of the translated Rust program by using test cases to check input/output equivalence, isolate faulty code when execution states deviate, and iteratively refine the translation using feedback from compilation and test errors. We empirically evaluate RustMap on 126 real-world programs, including 125 from Rosetta Code and a 7000+ line bzip2 implementation using GPT-4o as the LLM. RustMap shows promising results, guiding GPT-4o to produce idiomatic, readable, and functional Rust code with significantly less unsafe code than other tools, and revealing non-trivial translation patterns reusable for future research.

机构、总结、中文摘要均由AI分析而来,可能存在错误,请以论文正文为准。

↑