The C programming language has been foundational in building system-level software. However, its manual memory management model frequently leads to memory safety issues. In response, Rust has emerged as a memory-safe alternative. Moreover, automating the C-to-Rust translation empowered by the rapid advancements of the generative capabilities of LLMs is gaining growing interest for large volumes of legacy C code. Leveraging LLM for the C-to-Rust translation introduces distinct challenges, unlike the math or commonsense QA domains where the LLMs have been predominantly applied. First, the scarcity of parallel C-to-Rust datasets hinders the retrieval of suitable code translation exemplars for in-context learning. Second, unlike math or commonsense QA problems, the intermediate steps required for C-to-Rust are not well-defined. Third, it remains unclear how to organize and cascade these intermediate steps to construct a correct translation trajectory. While existing LLM-based approaches have achieved some success, they have relied on iterative code refinement along a single search trajectory on a C-to-Rust problem space and have not explored the use of systematic search mechanisms to navigate the space of possible refinement trajectories. To address these challenges in the C-to-Rust translation, we propose the MCTS-Guided LLM refinement technique for automated C-to-safe-Rust translation (LAC2R). LAC2R uses MCTS to systematically explore multiple refinement trajectories and organize the LLM-induced intermediate steps for correct translation. We experimentally demonstrated that LAC2R effectively conducts C-to-Rust translation on large-scale, real-world benchmarks. On small-scale benchmarks, LAC2R is the only method that simultaneously attains the highest safety ratio, perfect project-level correctness, and the fewest linter warnings among the compared methods.
翻译:C语言是构建系统级软件的基石。然而,其手动内存管理模型常导致内存安全问题。为此,Rust作为一种内存安全的替代方案应运而生。此外,借助大语言模型(LLM)生成能力的快速发展,自动化C到Rust翻译在大量遗留C代码处理中受到日益关注。与LLM主要应用的数学或常识问答领域不同,利用LLM进行C到Rust翻译面临着独特挑战。首先,并行C-Rust数据集的稀缺性阻碍了通过上下文学习获取合适的代码翻译示例。其次,与数学或常识问答问题不同,C到Rust翻译所需的中介步骤尚未明确定义。第三,如何组织与串联这些中介步骤以构建正确的翻译轨迹仍不明确。现有基于LLM的方法虽取得一定成效,但均依赖于在C到Rust问题空间沿单一搜索轨迹进行迭代式代码精化,未探索使用系统化搜索机制来遍历可能的精化轨迹空间。为应对C到Rust翻译中的这些挑战,我们提出基于MCTS引导的LLM精化技术,实现自动化C到安全Rust翻译(LAC2R)。LAC2R利用蒙特卡洛树搜索(MCTS)系统化地探索多条精化轨迹,并组织LLM产生的中介步骤以实现正确翻译。实验表明,LAC2R能够在大规模真实基准上有效执行C到Rust翻译。在小规模基准测试中,LAC2R是唯一同时实现最高安全性比率、完美项目级正确性以及最少lint警告的方法。