Large language models (LLMs) show promise in code translation due to their ability to generate idiomatic code. However, a significant limitation when using LLMs for code translation is scalability: existing works have shown a drop in translation success rates for code exceeding around 100 lines. We overcome this limitation by developing a modular approach to translation, where we partition the code into small code fragments which can be translated independently and semantically validated (that is, checking I/O equivalence). When this approach is applied naively, we discover that LLMs are unreliable when translating features of the source language that do not have a direct mapping to the target language, and that the LLM often gets stuck in repair loops when attempting to fix errors. To address these issues, we introduce two key concepts: (1) feature mapping, which integrates predefined translation rules with LLM-based translation to guide the LLM in navigating subtle language differences and producing semantically accurate code; and (2) type-compatibility, which facilitates localized checks at the function signature level to detect errors early, thereby narrowing the scope of potential repairs. We apply our approach to translating real-world Go codebases to Rust, demonstrating that we can consistently generate reliable Rust translations for projects up to 6,600 lines of code and 369 functions, with an average of 73% of functions successfully validated for I/O equivalence, considerably higher than any existing work.
翻译:大型语言模型(LLMs)因其生成地道代码的能力,在代码翻译领域展现出巨大潜力。然而,现有方法在可扩展性方面存在显著局限:研究表明,当代码量超过约100行时,翻译成功率会明显下降。为突破这一限制,我们提出了一种模块化的翻译方法,将代码分割为可独立翻译并能够进行语义验证(即检查输入输出等价性)的小型代码片段。直接应用该方法时,我们发现LLMs在翻译源语言中不存在直接映射到目标语言的特征时表现不可靠,且经常在尝试修复错误时陷入循环修正的困境。为解决这些问题,我们引入了两个关键概念:(1)特征映射——通过整合预定义的翻译规则与基于LLM的翻译,引导LLM处理细微的语言差异并生成语义准确的代码;(2)类型兼容性——在函数签名层面实施局部检查以早期检测错误,从而缩小潜在修复的范围。我们将该方法应用于真实世界的Go代码库到Rust的翻译实践,证明能够稳定地为多达6,600行代码、包含369个函数的项目生成可靠的Rust翻译版本,其中平均73%的函数通过了输入输出等价性验证,该成果显著超越了现有研究的水平。