LLM-Driven Multi-step Translation from C to Rust using Static Analysis

Tianyang Zhou, Haowen Lin, Somesh Jha, Mihai Christodorescu, Kirill Levchenko, Varun Chandrasekaran

TL;DR

Translating legacy C code into memory-safe, idiomatic Rust is notoriously difficult because existing transpilers rely heavily on unsafe blocks, while naive LLM translations introduce hallucinations and compile errors. SACTOR bridges this gap using a two-step translation pipeline guided by static analysis and verified incrementally via Foreign Function Interface (FFI) test harnesses. Across 200 programs, SACTOR produced 100% unsafe-free idiomatic Rust, with reasoning models like DeepSeek-R1 achieving up to a 93% translation success rate.

What Problem Does This Paper Address?

Decades of critical infrastructure remain written in C, leaving systems exposed to memory safety exploits like buffer overflows and use-after-free bugs. Rust provides modern, compile-time memory safety without performance penalties, making C-to-Rust migration highly desirable.

However, automated migration is fundamentally difficult:

  • Rule-based transpilers (e.g., C2Rust) produce direct syntactic mappings wrapped in Rust’s unsafe blocks, failing to leverage Rust's core safety features (ownership, borrowing, lifetimes).
  • Pure LLM approaches can generate idiomatic Rust, but they struggle with complex control flow, hallucinate pointer behaviors, and lack formal correctness guarantees.
  • Formal verification techniques (such as symbolic execution or fuzzing) struggle to scale to non-trivial C code due to compiler-inserted checks and standard library mismatches.

Methods

SACTOR (Structure-Aware C-to-Rust Translator) divides the translation and verification process into modular steps:

  1. Dependency Analysis & Task Division: A custom static analysis tool based on libclang parses the C code, extracts semantic dependencies (types, globals, and functions), and orders translation tasks topologically using depth-first search for circular dependencies.
  2. Step 1: C to Unidiomatic Rust: Translates C to syntactically equivalent Rust that retains C-like semantics, raw pointers, and unsafe blocks. Data types are transpiled using C2Rust, while functions are translated by the LLM using extracted dependency signatures.
  3. Step 2: Unidiomatic to Idiomatic Rust: Refines unidiomatic Rust into safe, idiomatic Rust. To replace raw pointers with safe types (Box, references, slices), SACTOR incorporates ownership, fatness, and mutability hints from Crown, a static pointer ownership analysis tool.
  4. FFI-based "Soft Equivalence" Verification: Rather than running heavy symbolic execution, SACTOR checks functional correctness via end-to-end (E2E) execution.
  5. For unidiomatic code, functions share the C ABI and are dynamically linked directly against the original C binary.
  6. For idiomatic code (where types and signatures diverge), SACTOR prompts the LLM to synthesize a bidirectional test harness that marshals data between C and Rust representations before calling the target function.
  7. Iterative Feedback Mechanism: If compilation or test execution fails, compiler diagnostics and runtime I/O logs (injected via a Rust procedural macro) are fed back into the prompt for up to 6 retry attempts.
+-----------+    libclang      +-----------------+   C2Rust / LLM   +------------------+
|  C Code   | --------------> | Fragment Order  | ---------------> | Unidiomatic Rust |
+-----------+                 +-----------------+                  +------------------+
                                                                             |
                                                                       Crown | Static Hints
                                                                             v
+------------------+           FFI Harness       +------------------------------------+
|  Idiomatic Rust  | <-------------------------- | Idiomatic Refinement & E2E Testing |
| (100% Safe Rust) |     (Compiler/Log Feedback) +------------------------------------+
+------------------+

Datasets

The authors evaluated SACTOR across two benchmark suites (100 C programs each) and two real-world C projects:

  • TransCoder-IR: 100 long-form C programs filtered to remove existing Rust translations, compilation errors, and memory leaks (verified using Valgrind). Includes existing E2E tests.
  • Project CodeNet: 100 programs that accept command-line inputs (argc/argv). Test cases were automatically synthesized using a custom SACTOR test generator.
  • Real-World Projects:
  • avl-tree (~1,000 LOC) – an AVL tree implementation with 12 unit/E2E test suites.
  • urlparser (~500 LOC) – an RFC-compliant URL parser evaluated using 10 E2E tests.

Key Insights and Ideas

  • Decoupling Syntax from Idiomatic Semantics: Forcing an LLM to simultaneously translate C syntax and redesign ownership semantics in a single step leads to frequent failures. Splitting the problem into C $\to$ Unidiomatic Rust and Unidiomatic $\to$ Idiomatic Rust significantly lowers cognitive load for the model.
  • Static Analysis as Prompt Guidance: LLMs struggle to infer whether a C pointer represents a single value, a dynamically sized array, an owned resource, or a borrowed reference. Injecting static ownership annotations from Crown eliminates this ambiguity.
  • The "Harness Bottleneck" in FFI Verification: When testing safe Rust code against legacy C drivers, the LLM must generate bridging harnesses to convert types (e.g., *const c_char $\leftrightarrow$ &str). Translation failures in larger projects often stemmed not from the translated algorithm itself, but from the LLM failing to construct valid type-marshalling wrappers.
  • Reasoning Models Outperform on Complex Logic: Models with reasoning chains (DeepSeek-R1) handled string conversions and complex pointer-arithmetic bounds far better than non-reasoning models (Claude 3.5, GPT-4o).

Key Results

  • Correctness & Success Rates:
  • DeepSeek-R1 achieved the highest overall success rate: 93% on TransCoder-IR and 84% on CodeNet.
  • GPT-4o followed with 80% and 79%, while Claude 3.5 Sonnet achieved 54% and 83% (struggling significantly with C-string semantics in TransCoder-IR).
  • Elimination of Unsafe Code:
  • While baseline tools like C2Rust, Crown, and C2SaferRust left substantial unsafe code (average unsafe fraction between 10.8% and 100%), SACTOR achieved 100% Unsafe-Free code across all successfully translated idiomatic programs.
  • Reduced Clippy lint alerts by up to $7\times$ compared to C2Rust and Crown.
  • Feedback Loop Impact: Iterative feedback dramatically aided weaker models (boosting Llama 3.3 70B's success rate by 17–21 percentage points), whereas high-tier models like GPT-4o saw minimal benefit.
  • Cost & Efficiency: GPT-4o and Gemini 2.0 Flash proved most token-efficient (~2,500–3,300 tokens/task). DeepSeek-R1 required $5\text{–}7\times$ more tokens (~13,500–17,900 tokens/task) due to its internal chain-of-thought generation.

Limitations and Future Work

  • Test Suite Dependency: SACTOR’s validation relies entirely on test coverage; subtle edge cases omitted from E2E test suites can slip through undetected.
  • Complex Language Features: The current tool struggles with:
  • Function pointers taking generic/void* arguments (Rust generics cannot easily be passed across an FFI boundary without raw pointers).
  • Complex preprocessor macros, inline assembly, and mutable global state.
  • Harness Synthesis Failures: In complex codebases like avl-tree and urlparser, valid idiomatic code was sometimes rejected purely because the LLM could not synthesize a working FFI bridging harness. Future extensions could integrate automated property-based fuzzing and formal verification to alleviate harness generation bottlenecks.

Summary updated

Abstract

Translating software written in C to Rust has significant benefits in improving memory safety while maintaining high performance. However, manual translation is cumbersome, error-prone, and often produces unidiomatic code. Large language models (LLMs) have demonstrated promise in producing idiomatic translations, but offer no correctness guarantees as they lack the ability to capture the semantic differences between the source and target languages. We propose SACTOR, an LLM-driven C-to-Rust translation tool that employs a two-step process: an initial "unidiomatic" translation to preserve semantics, followed by an "idiomatic" refinement to align with Rust standards. SACTOR leverages static analysis of the C source to handle pointer semantics and dependency resolution. To validate the correctness of step-wise translation, we use end-to-end testing via the foreign function interface. We evaluate the translation of $200$ programs from two datasets and two case studies, comparing the performance of GPT-4o, Claude 3.5 Sonnet, Gemini 2.0 Flash, Llama 3.3 70B and DeepSeek-R1 in SACTOR. Our results demonstrate that SACTOR achieves high correctness and enhanced idiomaticity, with the best-performing model (DeepSeek-R1) reaching 93\% and 84\% correctness (on each dataset, respectively), while generating more idiomatic, Rust-compliant code, reducing Clippy lint alerts by up to 7$\times$, and producing unsafe-free translations on both datasets compared to existing methods.
BibTeX
@inproceedings{zhou2026llm,
  author = {Tianyang Zhou and Haowen Lin and Somesh Jha and Mihai Christodorescu and Kirill Levchenko and Varun Chandrasekaran},
  title = {{LLM-Driven Multi-step Translation from C to Rust using Static Analysis}},
  booktitle = {Annual Meeting of the Association for Computational Linguistics},
  year = {2026},
  doi = {10.18653/v1/2026.acl-long.28},
}
Figure