Cpp2Rust/cpp2rust

GitHub: Cpp2Rust/cpp2rust

Cpp2Rust 是一个基于 clang AST 的语法驱动翻译器,能将 C++ 代码自动转换为完全安全的 Rust 代码。

Stars: 275 | Forks: 10

# Cpp2Rust Cpp2Rust 可以将 C++ 自动翻译为完全安全的 Rust。它是一个基于 clang AST 的语法驱动翻译器。 Cpp2Rust 的算法在发表于 PLDI 2026 的论文 [Cpp2Rust: Automatic Translation of C++ to Safe Rust](https://web.ist.utl.pt/nuno.lopes/pubs/cpp2rust-pldi26.pdf) 中有所描述。 ## 概述 Cpp2Rust 首先使用 clang 解析输入的 C++ 文件,并生成 AST。 随后,它会遍历 AST 并以字符串形式输出 Rust 代码,并在需要的地方(例如用于裸指针语义) 插入对 `libcc2rs` 运行时库的调用。 最后,使用 `rustfmt` 将 Rust 代码格式化并输出到单个 `.rs` 文件中。 默认情况下使用*引用计数模型*,该模型能够生成完全安全的 Rust。 此外,也可以通过 `--model=unsafe` 命令行参数使用不安全 Rust 生成器,以便进行调试和性能比较。 ### 运行时库 (`libcc2rs`) 生成的代码依赖于一个旨在简化翻译过程的运行时库。 C 指针会被转换为 `libcc2rs` 提供的 `Ptr` 类型。 `Ptr` 模拟了 C 指针语义(包括空指针、算术运算和别名),同时通过检查运行时操作来满足 Rust 的借用检查器。 ## 要求 在 Ubuntu 上,使用以下命令安装所需的依赖项: ``` sudo apt install libclang-22-dev clang++-22 ninja-build cmake curl -LsSf https://astral.sh/ruff/install.sh | sh ``` ## 构建 ``` mkdir build cd build cmake -GNinja .. ninja ninja check ``` ## 运行 ### 翻译单个文件 ``` ./build/cpp2rust/cpp2rust --file=.cpp -o=.rs ``` 默认情况下使用引用计数模型(输出完全安全的代码)。 如果需要生成不安全的 Rust: ``` ./build/cpp2rust/cpp2rust --file=.cpp -o=.rs --model=unsafe ``` **最小示例。** 给定 `hello.cpp`: ``` #include int main() { printf("hello world\n"); return 0; } ``` 运行 `./build/cpp2rust/cpp2rust --file=hello.cpp -o=hello.rs` 会生成: ``` pub fn main() { std::process::exit(main_0()); } fn main_0() -> i32 { println!("hello world"); return 0; } ``` 编译并运行: ``` rustc hello.rs -L ../libcc2rs/target/debug ./hello ``` ### 翻译整个程序 首先为您的项目生成一个 [`compile_commands.json`](https://clang.llvm.org/docs/JSONCompilationDatabase.html) 。在使用 CMake 时,只需额外添加一个标志: ``` cmake -DCMAKE_EXPORT_COMPILE_COMMANDS=ON .. ``` 然后运行: ``` ./build/cpp2rust/cpp2rust --dir= -o .rs ``` `` 必须是包含 `compile_commands.json` 的目录。 ## 测试套件 ``` # 运行所有测试 ninja check # 仅运行单元测试 ninja check-unit # 运行 libcc2rs 单元测试 ninja check-libcc2rs # 运行 libcc2rs-macros 单元测试 ninja check-libcc2rs-macros # 在有意修改后重新生成单元测试的预期输出 REPLACE_EXPECTED=1 ninja check-unit ```
标签:Bash脚本, C++, Rust, 代码转换器, 代码迁移, 可视化界面, 数据擦除, 编译器工具, 网络流量审计, 通知系统