Source-linked AI summary
SpeC2Rust: Specification-Driven Repository-Level C-to-Rust Translation
Junjie Yao, Xiongzheng Guan, Jia Feng, Yujia Chen, Hongliang Tian, Cuiyun Gao
TL;DR
Repository-level C-to-Rust translation still faces challenges in recovering project intent, maintaining cross-file organization, and scaling to larger projects. SpeC2Rust externalizes project knowledge into reusable specifications and uses them through generation and repair; on eight projects, it produces compilable, test-passing Rust, with lower cost and input-token usage than SmartC2Rust on five shared projects.
Problem
Existing approaches may fail to recover repository-level module and interface structure, and translation success tends to decrease as project size increases.
Source: §I · pp. 1–2Method
SpeC2Rust externalizes project knowledge in reusable specifications and applies them through project structuring, spec-guided generation, and layered repair.
Source: §I · p. 2Results
Across eight projects, SpeC2Rust produces compilable Rust that passes original end-to-end tests; on five projects shared with SmartC2Rust, it reduces monetary cost by 66.1% and input-token usage by 84.7%.
Source: §I · p. 2Takeaways & Limitations
On the eight evaluated projects, the final translations contain no raw-pointer declarations, raw-pointer dereferences, or unsafe lines of code.
Source: §I · p. 2, §VIII · p. 11Stage 1 must correctly recover module boundaries, interface relations, and behavioral constraints; errors can propagate into generation and repair.
Source: B. Threats to Validity · p. 10
Abstract
from arXiv · showhide
Legacy C codebases remain central to system software and performance-critical infrastructure, but their weak memory safety imposes security and maintenance risks. Recent C-to-Rust translation systems, including LLM-based translators, make automated migration increasingly feasible, yet they still struggle to recover repository-level intent, avoid raw pointers and unsafe constructs, maintain cross-file interfaces, and repair compilation and validation failures efficiently. We propose SpeC2Rust, a specification-driven pipeline for repository-level C-to-Rust translation. It has three stages: (1) Project-Intent Structuring, which decomposes a C repository into semantically coherent modules and generates persistent repository- and module-level specifications; (2) Spec-Guided Generation, which translates each Rust module against these specifications with a live symbol registry to preserve cross-file consistency; and (3) Layered-Feedback Repair, which batches repairs and injects only failure-relevant diagnostics, specification context, and source evidence for efficient compilation and test-driven correction. We evaluate SpeC2Rust on eight repository-level C projects. It generates Rust projects that compile and pass the original end-to-end tests, with no raw-pointer declarations, raw-pointer dereferences, or unsafe lines. On projects shared with an LLM-based baseline, SpeC2Rust reduces cost by 66.1% and input-token usage by 84.7%.
I. INTRODUCTION
Repository-level C-to-Rust migration must recover project intent, improve memory safety, preserve cross-file interfaces, and repair validation failures. SpeC2Rust externalizes project knowledge into reusable specifications and applies it during generation and repair.
- Existing approaches can pass end-to-end tests yet lose the original algorithmic logic, retain unsafe C-centered code, or fail to recover idiomatic module and interface structures.As project size increases, translation success may decrease, and single-file organization can weaken maintainability.Source: §I · pp. 1–2
- SpeC2Rust uses Project-Intent Structuring, Spec-Guided Generation, and Layered-Feedback Repair to externalize repository knowledge and reuse it through translation.Its repair stage batches failures, injects targeted evidence, and treats test scripts as read-only.Source: §I · p. 2
- The pipeline targets safer, clearer Rust reconstruction by replacing rigid C-oriented skeletons with more idiomatic abstractions and module organization.The paper presents this as a contribution of the approach.Source: §I · p. 2
- 66.1% lower monetary cost and 84.7% lower input-token usage on five SmartC2Rust-shared projects; across eight projects, translations compile and pass original end-to-end tests without raw-pointer declarations, dereferences, or unsafe lines.These results are reported for the repository-level translations.Source: §I · p. 2
II. MOTIVATING EXAMPLE
The c4 interpreter example contrasts skeleton-preserving translation with SpeC2Rust’s Rust-native reconstruction. It illustrates how the latter reorganizes code and state rather than retaining C-oriented structures.
- Skeleton-based translation keeps the Rust project layout close to the original C project and retains substantial unsafe code.The example uses c4, a small C compiler in the evaluation dataset.Source: §II · pp. 2–3
- In c4’s lexer, the skeleton-based version relies on a global raw pointer, extern "C" linkage, and pervasive unsafe operations.The translated logic remains tied to C-style control flow and memory-access patterns.Source: §II · p. 3
- SpeC2Rust reorganizes the lexer around C4 and C4Error, stores state in struct fields, and exposes failure cases through Result-typed interfaces.It also rewrites operations as methods over &mut self and uses helper functions such as scan_number().Source: §II · p. 3
III. APPROACH
SpeC2Rust first analyzes a C repository, partitions it into translation-oriented units, and generates persistent specifications that guide later translation and repair.
III. APPROACH
- The approach has three stages: project-intent analysis and specification, dependency-aware Rust generation, and repair using compiler diagnostics and test feedback.Source: §III · p. 3
A. Project-Intent Structuring
- Project-Intent Structuring analyzes the repository and produces structured specifications encoding project-level design intent for later stages.It comprises Static Analysis, Hierarchical Module Split, and Spec Generation.Source: A. Project-Intent Structuring · p. 3
1) Static Analysis:
- Static analysis parses C sources and headers into function and file records, then links call sites and data definitions into project-level graphs and serialized metadata.The metadata preserves source evidence for retrieval during generation and repair.Source: 1) Static Analysis · p. 3
2) Hierarchical Module Split:
- Hierarchical Module Split evaluates candidate modules using intra- and inter-module call edges, then refines remaining groups by struct access, name prefix, and source file.Oversized groups are chunked to fit context limits; the output includes module units and finer-grained cluster units.Source: 2) Hierarchical Module Split · p. 3
3) Spec Generation:
- Spec Generation creates module-level requirements, implementation plans, and executable task decompositions, plus project-level rewrite context and a translation contract.The documents provide context for both generation and repair.Source: 3) Spec Generation · p. 3
B. Spec-Guided Generation
Spec-Guided Generation uses Stage 1 specifications as primary context to translate the repository in dependency-aware order. It assembles focused per-file context and registers generated interfaces for reuse across files.
B. Spec-Guided Generation
- Stage 2 translates the project using Stage 1 specifications, with Context Assembly followed by Rust Code Generation.Source: B. Spec-Guided Generation · p. 3
1) Context Assembly:
- The file-level plan records generation order, source coverage, and Rust-file dependencies, then assembles each file’s context from its module specification, project rewrite context, and dependency interface summaries.Source: 1) Context Assembly · p. 4
2) Rust Code Generation:
- Generation proceeds in dependency order; a live symbol registry stores exported signatures and referenced symbols so later files can reuse prior interfaces without rereading the full repository.The system retrieves source excerpts or generated Rust when needed, resumes output-limited files across multiple passes, and applies lightweight fixes for duplicate definitions and cross-file reference errors.Source: 2) Rust Code Generation · p. 4
C. Layered-Feedback Repair
Layered-Feedback Repair aligns the C and Rust execution environments, normalizes structural artifacts, then uses compilation and behavioral feedback to repair the translated project. Specifications and focused evidence inform iterative repairs until compilation and end-to-end tests pass.
1) Execution Environment Alignment:
- The aligned environment records dependencies, working directories, I/O conventions, and test commands so both projects can be run consistently.These settings support collection of compiler diagnostics and C/Rust behavioral differences for later repair.Source: 1) Execution Environment Alignment · p. 5
2) Structural Normalization:
- Rule-based preprocessing removes formatting, module, syntax, and import artifacts before model-based repair focuses on substantive errors.Later rounds target issues such as type mismatches, ownership violations, and interface mismatches.Source: 2) Structural Normalization · p. 5
3) Compilation-Guided Repair:
- Compilation-guided repair batches related diagnostics by affected files and dependencies, then repairs each batch with specifications, source evidence, and repair memory.Major rounds can roll back and retry when progress stalls; Figure 5 depicts the five prompt layers.Source: 3) Compilation-Guided Repair · p. 5, Figure 5 · p. 5
4) Test-Driven Repair Closure:
- After compilation succeeds, the system compares original C and translated Rust test outcomes and repairs behavioral differences until all end-to-end tests pass.Repair inputs include minimized test differences, execution traces, and relevant code evidence; target mismatches include boundary conditions, integer behavior, error paths, and cross-module calls.Source: 4) Test-Driven Repair Closure · p. 5
IV. EXPERIMENTAL SETUP AND IMPLEMENTATION
The evaluation uses eight prior-work C projects with end-to-end shell tests, compares SpeC2Rust with four translation baselines, and measures safety, semantic equivalence, and cost.
1) Dataset.:
- The dataset contains eight C projects ranging from 418 to 49,757 lines, each accompanied by end-to-end shell tests.The evaluation reports repository scale and cross-file complexity, test-script provenance and coverage, and the number of Stage 1 modules.Source: 1) Dataset · pp. 5–6, Table I · p. 6
2) Baselines.:
- The four baselines are C2Rust, C2SaferRust, EvoC2Rust, and SmartC2Rust, with SmartC2Rust serving as the primary comparison point.They represent rule-based translation, safer rewriting of C2Rust output, skeleton-driven generation, and iterative feedback-driven LLM translation, respectively.Source: 2) Baselines · p. 6
3) Metrics:
- Evaluation measures safety, semantic equivalence, and practical overhead using safety counts, compilation and test outcomes, and model-use and runtime costs.Cost metrics include chats, input and output tokens, latency, and API cost.Source: 3) Metrics · p. 6
4) Implementation Details.:
The experiments preserve the original test scripts and evaluate SpeC2Rust on eight C projects across safety, semantic equivalence, cost, and component contributions. Across all eight repositories, it eliminates measured unsafe code and raw pointers.
4) Implementation Details.:
- The evaluation keeps test scripts unchanged, redirecting only the executable path to assess semantic preservation without LLM-driven test rewriting.All LLM-based experiments use the gpt-5.4 API model with max_tokens set to 8192.Source: 4) Implementation Details · p. 6
A. Research Questions
- The evaluation covers eight C projects and asks about translation safety, repository-level semantic equivalence, cost efficiency, and the contributions of major components.These questions define the evaluation’s four research-question areas.Source: §V · p. 6, A. Research Questions · p. 6
B. RQ1: Safety
- 100.0%: SpeC2Rust reduces raw-pointer declarations, raw-pointer dereferences, and unsafe lines by 100.0% in aggregate relative to C2Rust.It produces zero raw-pointer declarations, zero raw-pointer dereferences, and 0%/0 unsafe code on every evaluated project.Source: B. RQ1: Safety · pp. 6–7, Table II · p. 7
- Table II compares SpeC2Rust with representative C-to-Rust baselines on safety metrics, where lower values are better.The table marks best and tied-best values and uses “∼” for unsuccessful translations or unreported metrics.Source: Table II · p. 7
C. RQ2: Semantic Equivalence
SpeC2Rust completes and passes the original end-to-end tests for all eight projects, while its repair workload varies with project scale. On the five projects completed by both tools, it reduces cost, latency, and token use compared with SmartC2Rust.
C. RQ2: Semantic Equivalence
- All eight SpeC2Rust translations compile and pass the original end-to-end tests; it is the only evaluated method with full eight-project coverage and zero-unsafe outputs.SmartC2Rust fails to compile on four projects, while EvoC2Rust produces no successful translation in this dataset.Source: C. RQ2: Semantic Equivalence · p. 7, Table III · p. 7
- Repair iterations range from four for c4 to 65 for cflow, with cat requiring 22; larger code volume and richer cross-file dependencies align with more repair effort.These factors create more opportunities for build-level mismatches and test-observable semantic deviations during translation.Source: C. RQ2: Semantic Equivalence · p. 7
- Most projects finish with zero cargo clippy errors, while which and cat retain one each; all eight nevertheless pass the original end-to-end tests.Remaining warnings mainly involve code paths, helper functions, or interface fragments weakly exercised by the available tests.Source: C. RQ2: Semantic Equivalence · p. 7
D. RQ3: Cost
- 84.7% lower input-token usage and 77.3% lower latency: SpeC2Rust uses 1,797.89 K input tokens and 5,908 s, versus SmartC2Rust’s 11,723.39 K and 26,038 s.The comparison covers five common projects; output-token usage falls by 21.1% and chat count by 5.6%.Source: D. RQ3: Cost · p. 8
- On c4, both tools take six repair rounds, but SpeC2Rust uses 168.58 K cumulative input tokens versus SmartC2Rust’s 308.79 K, a 45.4% reduction.SpeC2Rust rebuilds each repair prompt from relevant specifications and observed failure evidence instead of carrying forward a growing prompt state.Source: D. RQ3: Cost · p. 8, Figure 6 · p. 8
- 66.1% lower total cost: SpeC2Rust costs $13.09 versus SmartC2Rust’s $38.61 on five common projects.SpeC2Rust completes all eight evaluated projects, while SmartC2Rust completes five.Source: D. RQ3: Cost · p. 8
E. RQ4: Ablation Study
Ablations show that removing any major component reduces compilation or test performance, with repair most affecting compilation and structuring or decomposition most affecting semantic results. The full pipeline also succeeds with a second underlying model, deepseek-v4-flash.
E. RQ4: Ablation Study
- The full system reaches 100.0% compile rate and 100.0% test pass rate across the eight-project dataset.The ablation evaluates compilation and the average percentage of original end-to-end tests passed.Source: E. RQ4: Ablation Study · p. 8, Table V · p. 9
Layered-Feedback Repair
- Without Layered-Feedback Repair, compile rate falls from 100.0% to 25.0%; the variant has no reported completed end-to-end test result.Without iterative compiler diagnostics, cross-file repair and build-level adjustments are difficult to resolve within the translation pipeline.Source: E. RQ4: Ablation Study · p. 8, Table V · p. 9
Project-Intent Structuring
- Without Project-Intent Structuring, compile rate is 87.5% but test pass rate falls to 25.0%.Without Stage 1 specifications, the test agent has less repository-level context to use the intended architecture to complete missing or incorrect functionality.Source: E. RQ4: Ablation Study · p. 8, Table V · p. 9
Hierarchical Decomposition
- Without hierarchical decomposition, compile rate falls to 62.5% and test pass rate to 12.3%.The study attributes the decline to less coherent translation units, making generated specifications and repair prompts less stable.Source: E. RQ4: Ablation Study · p. 8, Table V · p. 9
Other LLMs beyond GPT
- With deepseek-v4-flash, the full pipeline translates all eight projects and passes all tests at lower overall cost than the default setting.The configuration uses max_tokens of 32K to account for long reasoning traces counted within the output budget.Source: E. RQ4: Ablation Study · pp. 8–9
E. RQ4: Ablation Study
- Removing any component reduces compile rate or test pass rate; repair’s largest drop is in compilation, while structuring or decomposition’s largest drop is semantic.The study’s answer to RQ4 distinguishes the largest compilation decline from the largest semantic decline.Source: E. RQ4: Ablation Study · pp. 8–9
VI. DISCUSSION
The robust_getcwd case contrasts a test-oriented translation that diverges from the C algorithm with SpeC2Rust’s intent-preserving reconstruction. The study’s validity is bounded by Stage 1 knowledge quality, CLI-only evaluation, and the limits of end-to-end tests.
A. Why SpeC2Rust Works ?
- SmartC2Rust replaces robust_getcwd’s directory-walking algorithm with a simpler current-directory call, while SpeC2Rust preserves the traversal, inode-based lookup, and modular organization.SpeC2Rust’s specifications and hierarchical module split provide focused context for reconstructing the intended behavior.Source: 2) SpeC2Rust: intent-preserving… · p. 9, 1) SmartC2Rust · p. 9
B. Threats to Validity
- LLM-based runs can vary in implementations, repair trajectories, and token costs; the study reduces this threat by running each project multiple times and reporting averages.Stage 1 errors in module boundaries, interfaces, or behavioral constraints may propagate into generation and repair.Source: B. Threats to Validity · pp. 9–10
- Stage 1 knowledge errors can propagate into generation and repair, and ablations indicate that SpecGen and hierarchical decomposition affect end-to-end correctness.Missing behavioral constraints or incorrect decomposition of tightly coupled functions and data structures may leave repair context incomplete.Source: B. Threats to Validity · p. 10
- Evaluation covers eight repository-level CLI C projects, not libraries, limiting how broadly findings may generalize; repository-level validation reduces but does not eliminate contamination concerns.The task’s repository reconstruction, cross-file consistency, compilation repair, and test validation reduce—but do not eliminate—the contamination concern.Source: B. Threats to Validity · p. 10
- Passing original end-to-end tests does not establish full behavioral equivalence because untested paths may still be incorrect.Remaining clippy warnings may reflect weakly exercised helper code, fallback paths, or interface fragments; reported costs also depend on experimental model pricing.Source: B. Threats to Validity · p. 10
VII. RELATED WORK
Related work spans safety-oriented translation, analysis- and LLM-guided generation, and feedback-driven repair, with persistent repository specifications distinguishing SpeC2Rust’s approach. The conclusion reports successful compilation and end-to-end tests across eight projects, alongside lower cost, latency, and input-token use than SmartC2Rust on five shared projects.
VII. RELATED WORK
- Safety-oriented translators improve on direct transpilation, but mainly refine C-oriented skeletons rather than rebuilding repositories around Rust-side specifications and module intent.C2Rust is described as a canonical rule-based approach that largely preserves the original C decomposition; removing raw pointers and unsafe code while preserving semantic equivalence remains difficult.Source: §VII · p. 10
- Analysis- and LLM-guided translators add structural guidance, but generally use structure, analysis facts, or specifications as prompt context rather than persistent artifacts reusable across generation and repair.Prior work reports compilation failures, inconsistency, and translation-induced bugs in LLM-based Rust translation,.Source: §VII · p. 10
- Feedback-driven systems use compiler and test feedback for iterative correction, but SmartC2Rust’s heavy repair reliance can permit hallucinated pseudoimplementations that pass tests superficially.Source: §VII · p. 10
VIII. CONCLUSION
- Across eight open-source C projects, SpeC2Rust compiled and passed original end-to-end tests while eliminating raw-pointer declarations, raw-pointer dereferences, and unsafe lines; on five shared projects it reduced cost 66.1%, latency 77.3%, and input-token usage 84.7%.The conclusion proposes extending evaluation to broader C systems, including libraries, and combining specification-guided translation with stronger validation such as fuzzing and differential testing.Source: §VIII · p. 11