HeadlinesBriefing favicon HeadlinesBriefing.com

Cpp2Rust: C++ to Rust translator

Hacker News •
×

Cpp2Rust offers an automatic translation process from C++ to safe Rust, leveraging clang's Abstract Syntax Tree (AST) for parsing. The tool traverses the AST and generates Rust code, integrating calls to a runtime library, `libcc2rs`, to handle C pointer semantics safely within Rust's borrow checker. This approach aims to facilitate migration from C++ to Rust, providing a path to memory-safe code.

The generated Rust code defaults to a reference counting model, ensuring full safety. For debugging or performance analysis, an option exists to produce `unsafe` Rust via the `--model=unsafe` command-line argument. The `libcc2rs` runtime library introduces a `Ptr<T>` type that mirrors C pointer behavior, including null checks and arithmetic, while strictly adhering to Rust's safety guarantees through runtime checks.

To use Cpp2Rust, users first parse C++ source files using clang, generating an AST. The tool then processes this AST to output Rust code, which is subsequently formatted with `rustfmt`. The project includes a test suite accessible via `ninja check`. For larger projects, generating a `compile_commands.json` file, often achieved with CMake's `CMAKE_EXPORT_COMPILE_COMMANDS=ON` flag, enables directory-based translation.