p2r is a static Python to Rust transpiler that converts statically typed Python code into idiomatic Rust. It bridges Python's simplicity with Rust's speed and safety, currently supporting imperative code, basic classes, and fundamental built-ins.
- Two-pass compilation for declarations and statements.
- Strong type unification with Rust-style type safety.
- Automatic translation of Python
range()to Rust ranges. - Full elimination of
UNKNOWNtypes in output. - Statement support: variables, assignments,
if/else,while,for,return. - Methods and struct generation from Python classes.
- f-string to
format!conversion. - Basic ownership inference and
clone()handling. - Integrated build and optional execution of Rust output.
- Pylance-clean Python codebase.
- Flexible file handling: retains
.rsand places executables/debug symbols alongside source.
- Subset of Python: dynamic features, advanced data structures beyond lists/dicts, and complex OOP are unsupported.
- Type annotations required.
- Rust error handling (
Result) not fully implemented; uses.unwrap(). - Borrow checker is only conservatively handled.
- No module or import handling.
- Limited standard library mapping (
print,len,str,int,float,range).
- Python 3.8+
- Rust toolchain (
rustcandcargo)
git clone https://github.com/pro-grammer-SD/p2r.git
cd p2rPython files must include type annotations. Example:
x: int = 42
print(f"x = {x}")
y: int = x + 10
print(y)
def add(a: int, b: int) -> int:
return a + b
result: int = add(5, 3)
print(result)
nums: list[int] = [1, 2, 3]
for n in nums:
print(n)
for i in range(3):
print(i)
msg: str = "Hello"
print(msg)
flag: bool = True
if flag:
print("Flag is true")python3 p2r.py example.pyGenerates example.rs and compiles to example/example.exe.
--output/-o: Specify Rust file name.--no-compile: Only generate.rs.--run: Execute Rust binary after compilation.--keep-pdb: Keep Windows.pdbdebug file.
MIT License β see LICENSE.