rusty-cpp
Bringing Rust's safety to C++ through:
1. Static Borrow Checker - Compile-time ownership and lifetime analysis via rusty-cpp-checker.
2. Safe Types - Box<T>, RefCell<T>, Vec<T>, HashMap<K,V>, etc.
3. Rust Idioms - Send/Sync traits, RAII guards, type-state patterns, Result<T,E>/Option<T>, etc.
1. Borrow Checking and Lifetime Analysis
π― Vision
This project aims to catch memory safety issues at compile-time by applying Rust's proven ownership model to C++ code. It helps prevent common bugs like use-after-move, double-free, and dangling references before they reach production.
Though C++ is flexible enough to mimic Rust's idioms in many ways, implementing a borrow-checking without modifying the compiler system appears to be impossible, as analyzed in this document.
We provide rusty-cpp-checker, a standalone static analyzer that enforces Rust-like ownership and borrowing rules for C++ code, bringing memory safety guarantees to existing C++ codebases without runtime overhead. rusty-cpp-checker does not bringing any new grammar into c++. Everything works through simple annoations such as adding // @safe enables safety checking on a function.
Example
Here's a simple demonstration of how const reference borrowing works:
// @safe
void
// @safe
void
Analysis Output:
Rusty C++ Checker
Analyzing: example.cpp
β Found 2 violation(s) in example.cpp:
Cannot create mutable reference to 'value': already immutably borrowed
Cannot create mutable borrow 'mut_ref': 'value' is already borrowed by 'const_ref'
β¨ Features
Core Capabilities
- π Borrow Checking: Enforces Rust's borrowing rules (multiple readers XOR single writer)
- π Ownership Tracking: Ensures single ownership of resources with move semantics
- β³ Lifetime Analysis: Validates that references don't outlive their data
Detected Issues
- Use-after-move violations
- Multiple mutable borrows
- Dangling references
- Lifetime constraint violations
- RAII violations
- Data races (through borrow checking)
π¦ Installation
Quick Install (Recommended)
The easiest way to install rusty-cpp is using our install script, which automatically detects your OS and installs all dependencies:
# One-liner install (detects OS, installs deps, builds from source)
|
Or clone and run locally:
Supported platforms:
- macOS (via Homebrew)
- Ubuntu/Debian (apt)
- Fedora (dnf)
- CentOS/RHEL 8+ (dnf)
- Arch Linux (pacman)
β οΈ Build Requirements (Manual Installation)
If you prefer manual installation, this tool requires the following native dependencies to be installed before building from source or installing via cargo:
- Rust: 1.70+ (for building the analyzer)
- LLVM/Clang: 16+ (for parsing C++ - required by clang-sys)
- Z3: 4.8+ (for constraint solving - required by z3-sys)
Note: These dependencies must be installed system-wide before running cargo install rusty-cpp or building from source. The build will fail without them.
Installing from crates.io
Once you have the prerequisites installed:
# macOS: Set environment variable for Z3
# Linux: Set environment variable for Z3
# Install from crates.io
# The binary will be installed as 'rusty-cpp-checker'
Building from Source
macOS
# Install dependencies
# Clone the repository
# Build the project
# Run tests
# Add to PATH (optional)
Note: The project includes a .cargo/config.toml file that automatically sets the required environment variables for Z3. If you encounter build issues, you may need to adjust the paths in this file based on your system configuration.
Linux (Ubuntu/Debian)
# Install dependencies (LLVM 16+ required)
# Clone and build
Windows
# Install LLVM from https://releases.llvm.org/
# Install Z3 from https://github.com/Z3Prover/z3/releases
# Set environment variables:
# Build
π Usage
Basic Usage
# Analyze a single file
# Analyze with verbose output
# Output in JSON format (for IDE integration)
Standalone Binary (No Environment Variables Required)
For release distributions, we provide a standalone binary that doesn't require setting environment variables:
# Build standalone release
# Install from distribution
# Or use directly
See RELEASE.md for details on building and distributing standalone binaries.
Environment Setup (macOS)
For convenience, add these to your shell profile:
# ~/.zshrc or ~/.bashrc
π‘οΈ Safety System
The borrow checker uses a two-state safety system with automatic header-to-implementation propagation:
Two Safety States
@safe- Functions with full borrow checking and strict calling rules@unsafe- Everything else (unannotated code is @unsafe by default)
Calling Rules Matrix
| Caller β Can Call | @safe | @unsafe |
|---|---|---|
| @safe | β Yes | β No (use @unsafe block) |
| @unsafe | β Yes | β Yes |
Safety Rules Explained
// @safe
void
// @unsafe (or no annotation - same thing)
void
Key Insight: This is a clean two-state model - code is either @safe or @unsafe. Unannotated code is @unsafe by default. To call anything unsafe from @safe code, wrap it in an @unsafe { } block.
Header-to-Implementation Propagation
Safety annotations in headers automatically apply to implementations:
// math.h
// @safe
int ;
// @unsafe
void ;
// math.cpp
int
void
STL and External Libraries
By default, all STL and external functions are @unsafe, meaning @safe functions cannot call them directly. You have two options:
Option 1 (Recommended): Use Rusty structures
// @safe
void
Option 2: Use @unsafe blocks for STL
// @safe
void
Option 3: Mark specific external functions as [safe] via external annotations
If you've audited an external function and want to call it directly from @safe code:
// @external: {
// my_audited_function: [safe, () -> void]
// }
void ; // External function you've audited
// @safe
void
See Complete Annotations Guide for comprehensive documentation on all annotation features, including safety, lifetime, and external annotations.
π Examples
Example 1: Use After Move
// @safe
void
Output:
Rusty C++ Checker
Analyzing: example.cpp
β Found 1 violation(s) in example.cpp:
Use after move: cannot dereference_write (via operator*) variable 'ptr1' because it has been moved
Example 2: Multiple Mutable Borrows
// @safe
void
Output:
Rusty C++ Checker
Analyzing: example.cpp
β Found 3 violation(s) in example.cpp:
Cannot create mutable reference to 'value': already mutably borrowed
Cannot create mutable borrow 'ref1': 'value' is already borrowed by 'ref2'
Cannot create mutable borrow 'ref2': 'value' is already borrowed by 'ref1'
Example 3: Lifetime Violation
// @safe
int&
Output:
Rusty C++ Checker
Analyzing: example.cpp
β Found 2 violation(s) in example.cpp:
Safe function 'dangling_reference' returns a reference but has no @lifetime annotation
Cannot return reference to local variable 'local'
ποΈ Architecture
βββββββββββββββ ββββββββββββ ββββββββββ
β C++ Code ββββββΆβ Parser ββββββΆβ IR β
βββββββββββββββ ββββββββββββ ββββββββββ
β β
(libclang) βΌ
ββββββββββββββββ
βββββββββββββββ ββββββββββββ β Analysis β
β Diagnostics βββββββ Solver βββββ Engine β
βββββββββββββββ ββββββββββββ ββββββββββββββββ
β β
(Z3) (Ownership/Lifetime)
Components
- Parser (
src/parser/): Uses libclang to build C++ AST - IR (
src/ir/): Ownership-aware intermediate representation - Analysis (
src/analysis/): Core borrow checking algorithms - Solver (
src/solver/): Z3-based constraint solving for lifetimes - Diagnostics (
src/diagnostics/): User-friendly error reporting
π Advanced Features
Using Rusty Structures (Recommended)
RustyCpp provides safe data structures that integrate seamlessly with the borrow checker:
// @safe
void
For STL structures, use @unsafe blocks:
// @safe
void
See Complete Annotations Guide for all annotation features.
External Function Annotations
Annotate third-party functions with safety and lifetime information without modifying their source.
By default, all external functions are @unsafe. You can:
- Use
@unsafeblocks to call them from@safecode - Mark specific functions as
[safe]if you've audited them
// @external: {
// // Mark as [safe] if you've audited the function
// my_audited_function: [safe, () -> void]
//
// // Mark as [unsafe] with lifetime info for documentation
// strchr: [unsafe, (const char* str, int c) -> const char* where str: 'a, return: 'a]
// malloc: [unsafe, (size_t size) -> owned void*]
// }
void ;
// @safe
void
See Complete Annotations Guide for comprehensive documentation on safety annotations, lifetime annotations, and external annotations.
2. Safe Type Alternatives
RustyCpp provides drop-in replacements for C++ standard library types with built-in safety guarantees:
Available Types
Smart Pointers
rusty::Box<T>- Single ownership pointer with move-only semanticsrusty::Box<Widget> widget = ; auto widget2 = ; // OK: explicit ownership transfer // widget.get(); // ERROR: use-after-move detected
Interior Mutability
rusty::RefCell<T>- Runtime borrow checking for interior mutabilityrusty::RefCell<int> ; auto mut_ref = cell.; // OK: previous borrow ended
Containers
-
rusty::Vec<T>- Dynamic array with iterator invalidation detectionrusty::Vec<int> vec = ; auto it = vec.; // vec.push_back(4); // ERROR: would invalidate iterator -
rusty::HashMap<K, V>- Hash map with safe concurrent access patterns -
rusty::HashSet<T>- Hash set with ownership semantics -
rusty::Rc<T>- Reference counted pointer (single-threaded) -
rusty::Arc<T>- Atomic reference counted pointer (thread-safe)
Utility Types
rusty::Option<T>- Explicit handling of optional valuesrusty::Result<T, E>- Explicit error handling
Usage
Include the headers:
These types are designed to work seamlessly with the borrow checker and enforce Rust's safety guarantees at runtime.
3. Rust Design Idioms
RustyCpp implements key Rust design patterns for safer concurrent programming:
Thread Safety Traits
Send Trait (Explicit Opt-In System)
RustyCpp implements Rust's Send trait using an explicit opt-in system that prevents accidental data races at compile-time:
// β
Primitives are pre-marked as Send
auto = rusty::sync::mpsc::channel<int>;
// β
Rusty types are Send if their content is Send
auto = rusty::sync::mpsc::channel<rusty::Arc<int>>;
// β Rc is NOT Send (non-atomic reference counting)
auto = rusty::sync::mpsc::channel<rusty::Rc<int>>; // Compile error!
// β Unmarked user types are NOT Send (must explicitly mark)
;
auto = rusty::sync::mpsc::channel<MyType>; // Compile error!
How to mark your types as Send:
// Method 1: Static marker (recommended for your types)
;
// Method 2: External specialization (for third-party types)
Key Features:
- Safe by default: Types are NOT Send unless explicitly marked
- Compositional safety:
struct { Rc<T> }is automatically rejected (no Send marker) - Clear errors: Compiler tells you exactly how to fix the issue
- No deep analysis needed: Simple marker check at compile-time
Example - Compositional Safety:
// Without marker, this is NOT Send (safe!)
;
auto = channel<ContainsRc>; // β Compile error!
// Error: ContainsRc must be Send (marked explicitly)
// Arc is thread-safe, so use it instead
;
auto = channel<ThreadSafeVersion>; // β Works!
MPSC Channel (Multi-Producer Single-Consumer)
Thread-safe message passing channel, identical to Rust's std::sync::mpsc:
// or
using namespace rusty::sync::mpsc::lockfree; // or ::mutex
void
Two Implementations Available:
-
Lock-Free (
mpsc_lockfree.hpp) - Recommended- 28 M msg/s throughput, 3.3 ΞΌs p50 latency
- Batch operations (4x faster under contention)
- Wait-free consumer, lock-free producers
- See User Guide and Developer Guide
-
Mutex-Based (
mpsc.hpp)- Simple, straightforward implementation
- Lower throughput but easier to understand
- Good for low-frequency communication
Common Features:
- Blocking operations:
send(),recv() - Non-blocking operations:
try_send(),try_recv() - Disconnection detection
- Type-safe with Send constraint
- Rust-compatible API
Sync Trait
Compile-time marker for types safe to share references between threads:
concept Sync = /* implementation */;
RAII Guards
Scope-based resource management following Rust's guard pattern:
// MutexGuard automatically unlocks on scope exit
auto guard = mutex.;
// ... use protected data ...
// Guard destroyed here, mutex automatically unlocked
Type-State Patterns
Encode state machines in the type system:
;
;
;
File<Unopened> ;
File<Opened> opened = file.; // State transition via move
std::string line = opened.; // OK
Error Handling
Rust-style Result and Option types:
rusty::Result<int, std::string> ;
rusty::Option<int> ;
// Pattern matching style
auto result = ;
if else
Tips in writing rusty c++
Writing C++ that is easier to debug by adopting principles from Rust.
Being Explicit
Explicitness is one of Rust's core philosophies. It helps prevent errors that arise from overlooking hidden or implicit code behaviors.
No computation in constructors/destructors
Constructors should be limited to initializing member variables and establishing the object's memory layoutβnothing more. For additional initialization steps, create a separate Init() function. When member variables require initialization, handle this in the Init() function rather than in the constructor.
Similarly, if you need computation in a destructor (such as setting flags or stopping threads), implement a Destroy() function that must be explicitly called before destruction.
Composition over inheritance
Avoid inheritance whenever possible.
When polymorphism is necessary, limit inheritance to a single layer: an abstract base class and its implementation class. The abstract class should contain no member variables, and all its member functions should be pure virtual (declared with = 0). The implementation class should be marked as final to prevent further inheritance.
Use move and disallow copy assignment/constructor
Except for primitive types, prefer using move instead of copy operations. There are multiple ways to disallow copy constructors; our convention is to inherit from the boost::noncopyable class:
;
If copy from an object is necessary, implement move constructor and a Clone function:
Object obj1 = ; // move can be omitted because it is already a right value.
Memory Safety, Pointers, and References
No raw pointers
Avoid using raw pointers except when required by system calls, in which case wrap them in a dedicated class.
Use POD types
Try to use POD types if possible. POD means "plain old data". A class is POD if:
- No user-defined copy assignment
- No virtual functions
- No destructor
Incrementally Migrate to Rust (C++/Rust Interop)
Some languages (like D, Zig, and Swift) offer seamless integration with C++. This makes it easier to adopt these languages in existing C++ projects, as you can simply write new code in the chosen language and interact with existing C++ code without friction.
Unfortunately, Rust does not support this level of integration (perhaps intentionally to avoid becoming a secondary option in the C++ ecosystem), as discussed here. Currently, the best approach for C++/Rust interoperability is through the cxx/autocxx crates. This interoperability is implemented as a semi-automated process based on C FFIs (Foreign Function Interfaces) that both C++ and Rust support. However, if your C++ code follows the guidelines in this document, particularly if all types are POD, the interoperability experience can approach the seamless integration offered by other languages (though this remains to be verified).
Closely related projects to watch
Two projects that (attempt to) implement borrow checking in C++ at compile time are Circle C++, and Crubit.
β οΈ Note: This is an experimental tool. Use it at your own discretion.