The pytors command transpiles Python 3.14 programs into a single Rust source file that needs no external crates.
Type hints and changes to the input program are not required.
This is an incomplete alpha release undergoing a direct-code-generation rewrite.
The public CLI and API either generate typed Rust or return a source-positioned
E006 diagnostic. A failed lowering never selects another execution backend.
Required language and library coverage remains unfinished; rejecting an
unimplemented program is not completion of that requirement.
See COMPATIBILITY.md for the current public boundary and
API_SUPPORT.md for the retained internal library inventory.
Transpilation requires Python 3.14 or later. Compiling the generated code requires Rust 1.85 or later. The compiled executable needs neither Python nor additional source files.
python3 -m pip install -e .
pytors examples/sum.py -o /tmp/main.rs
rustc --edition=2021 -O /tmp/main.rs -o /tmp/main
printf '4\n1 2 3 4\n' | /tmp/mainYou can also run the transpiler from the repository root without installing it:
python3 -m py2fastrust examples/sum.py -o /tmp/main.rsThe browser converter provides a black-and-white, two-panel interface for the same compiler using Python 3.14 in a Pyodide module worker. It accepts a single source file and keeps translation in the browser after the runtime assets load. See its documentation for local verification and GitHub Pages deployment.
The integer mode applies to the entire directly generated program:
pytors main.py -o main.rs # i64 (default)
pytors main.py -o main.rs --int i128
pytors main.py -o main.rs --int bigintIn i64 and i128 modes, integer literals, conversions, and arithmetic results wrap to the selected signed width,
with one exception. When a program contains a constant integer expression that does not fit the width, such as
(1 << 1000) - 1 or 10**30, those constants, left shifts that are not proven to fit, and arithmetic or
comparisons involving such values are exact Python integers. All other values keep the native width. Large
bitmasks therefore stay exact while the rest of the program runs on native integers. The exception applies
only where the value reaches assignments, arithmetic, comparisons, returns, containers, printing, or functions
the program defines. A constant passed directly to another builtin or method, used as an index or slice bound,
or used as a % format operand keeps the width normalization of that operation. So does a name whose reads
include such a use. A constant expression whose own value fits is folded with the mode's width. If an
operation on an exact value is not supported yet, or a value may be either a bool or an exact integer, the
whole program uses the mode's wrapping instead.
Use --int bigint when you need Python's arbitrary-precision integer behavior everywhere.
The arithmetic option selects the semantics of integer //, %, and divmod in i64 and i128 modes:
pytors main.py -o main.rs --arith rust # default
pytors main.py -o main.rs --arith pythonrust uses Rust's truncating division: the quotient rounds toward zero and the remainder takes the
dividend's sign, so -7 // 2 is -3 and -7 % 2 is -1. It needs no sign correction and lets Rust
optimize constant divisors directly. python keeps Python's floor division, where -7 // 2 is -4
and -7 % 2 is 1. Both modes agree whenever the operands have the same sign. bigint mode always
uses Python semantics, and the generated header records the selected arithmetic.
The generated file includes the BigInt runtime, so Cargo and additional crates are unnecessary.
Range termination, indices, and allocation sizes use separate checked calculations.
Strings default to ASCII mode for competitive-programming inputs. Their length,
indices, slices, and count bounds use bytes without scanning the string to
detect ASCII on each access. Use Unicode mode for non-ASCII text and Python's
code-point indexing:
pytors main.py -o main.rs --string-mode unicodeThe API setting is TranspileOptions(string_mode="unicode"); the browser
provides the same selection. ASCII mode assumes that strings contain ASCII.
It does not automatically switch models when non-ASCII input is encountered.
The ASCII profile also selects ASCII numeric-text parsing and omits Unicode
property tables and code-point indexing caches. Buffered text input rejects
non-ASCII bytes; binary streams remain byte streams. Unicode mode enables
non-ASCII digits, whitespace, and code-point operations where supported.
Use --license none to omit the generated program's license text. The output
records LICENSE: NONE and keeps the original source and generator metadata.
An existing source license still takes precedence, and notices for retained
third-party code or data remain included. Unlicense is a separate license
choice; the default remains CC0-1.0.
Conversion options can be recorded in the initial comment block:
# pytors: --int i128 --license Unlicense
n = int(input())
print(n * n)Source options take precedence over command-line and Python API settings. The parser reads blank lines and comments, including shebang and encoding comments, and stops at the first Python statement. Later directives have no effect.
Allowed options are --int, --arith, --string-mode, --license, --module-path, --include-module,
--no-optimize, --optimize, --no-compact, --compact, -o/--output, and --check.
Input filenames, help, and version options are not accepted in directives.
If a scalar option appears more than once, the last value wins.
Source declarations of repeated options, such as --module-path and --include-module,
replace the corresponding CLI or API list; repeated source declarations accumulate within that list.
Relative paths in directives are resolved from the input file's directory.
Output paths and --check affect the CLI only. The Python API returns a result and never writes files,
even when those options appear in the source.
The direct path recognizes proved collections.deque imports using the
compiler's actual module resolution. A user module with the same name is not
silently replaced by that specialization.
Resolved heapq min/max heap operations and bisect searches/insertions use
typed list helpers. Their current payload and callable-key boundaries are
listed in COMPATIBILITY.md.
It also recognizes trusted sys.stdin and sys.stdin.buffer readers, including
captured read/readline aliases and local imports inside ordinary functions.
Text and byte reads retain their different newline, EOF, whitespace, and
integer-parsing rules. Both use the same buffered input stream.
Fixed-name imports bundle user modules and pure-Python packages into the single
Rust file when their operations have direct lowering. Original ASTs and scopes
stay separate. Imports initialize namespaces at their original execution point,
cache partial modules during circular imports, and preserve aliases, shared
values, and functions' defining namespaces. This includes function-local and
relative imports; generated programs do not read Python files at runtime.
Bundled atcoder modules are resolved automatically, without installing a host
Python package. Their algorithms still require supported language operations;
this is not a claim that every AtCoder Library module already compiles.
sortedcontainers is also resolved without a host package: an independent
implementation of SortedList, SortedSet and SortedDict (sortedcontainers
2.4 behavior for values without a key function) is bundled and compiled like
other source modules. Bisection, positional access and deletion, irange,
islice, set algebra, sorted dictionary views, comparisons, repr and error
messages follow the upstream package. Key functions, slicing, sequence
arithmetic and other upstream methods outside this implementation are
positioned conversion errors rather than different runtime behavior.
--include-module remains a recognized but unsupported option: runtime
compile/eval/exec and their access to prebundled modules still require
implementation. Requests receive a diagnostic even when ordinary static imports
are present. Unsupported operations in imported modules also produce positioned
diagnostics; the retained internal interpreter is never selected.
The input file's directory remains the default module search path.
Actual builtin modules take precedence over that path. Their catalog is the
intersection of supported module adapters with sys.builtin_module_names from
the CPython 3.14 build running the converter, including Pyodide. Other standard
modules keep normal path precedence, so user files and regular packages can
shadow them.
from py2fastrust import TranspileOptions, transpile
result = transpile(
'n = int(input())\nprint(n * n)\n',
TranspileOptions(integer="i128", filename="solution.py", license="Unlicense"),
)
if result.success:
print(result.rust_source)
else:
for diagnostic in result.diagnostics:
print(diagnostic)The shared frontend parses each source once with the official ast and
symtable APIs, validates contextual syntax, and resolves fixed-name imports
before native lowering. All direct emitters consume the same read-only source
unit and lexical metadata. No VM instruction compilation is needed for public
conversion. Only requested modules are resolved; __future__ is not implicitly
loaded.
A shared semantic graph solves allocation field constraints and loop-header
binding shapes before ordinary Rust lowering, including empty collections and
possibly unbound names. It contains compile-time facts and typed control-flow
edges; the generated program executes its Rust statements directly. Nested lists
with proved immutable payloads retain typed shared row identities across aliases,
ordinary function calls, parent replacement/clearing, and live iteration in all
integer modes. Flat uniquely owned arrays keep their existing vector storage.
List storage is selected separately from Python's value types. Proved private
homogeneous arrays use Vec<T>. Fixed heterogeneous local records and class
fields can use Rust tuples when stable position types and constant slot uses
are proved. Lists whose elements can change between known types use a vector
of a finite element enum.
Private nested arrays with freshly constructed rows and proved indexed or
length-only uses can use Vec<Vec<T>> and deeper vectors. Repeated shared
rows, escaping row references and row replacement retain shared storage.
Direct iteration over a private vector reads one element at a time and sees
subsequent element updates, appends and pops. Lists with observable aliases or
unproved ownership retain shared handles so updates and object identity stay
consistent with Python.
Callback context analysis separates the defining module from live lexical captures. A callback that only reads captured builtin scalars keeps its actual closure cells without switching the caller's module namespace. Plain receiver methods and captured source-callable payloads acquire their own defining contexts. Proved fixed-width constant divisors lower to wrapping floor arithmetic while preserving both original operand evaluations and unbound-name errors. Short closed leaf bodies expose their typed arithmetic to Rust's optimizer.
Shared instances with proved scalar-only fields retain their reference identity while definite initialization removes optional field storage and presence checks. Read-only field parameters can borrow the actual instance without incrementing its reference count. Constant propagation includes registered source operator writes and distinguishes dictionary value replacement from mutations through a retrieved alias. Dictionary membership examines key protocols; stored values do not invalidate an otherwise closed comparison.
In programs without lifetime observers, statement temporaries end with their source statement. Loop-aware liveness can release dead local scalar-instance handles earlier; captures, loop-carried values, zero-iteration exits and saved object representations retain their required lifetimes. Sequential calls do not add to the certified maximum simultaneous recursion depth.
For sealed scalar instance layouts, fresh constructors and source functions can
produce concrete Rust data before a shared handle is needed. Read-only formals
accept either shared instances or that concrete data. A loop-local value becomes
a data snapshot only when its binding stays within one iteration, every read
follows its assignment, and all reached source calls preserve existing instance
fields. Captures, observable identity and mutations through aliases reject that
transformation. Fresh list replacements reuse storage only when the previous
instance has no other owners. Closed loops borrow the underlying typed Vec once;
callees that could access an alias of that list prevent the extended borrow.
Canonical integer str maps join by writing directly to one string buffer,
without allocating a string for each element. Saved map cursors retain their
actual shared iteration state; custom callbacks keep their original calls.
BigInt keeps values that fit signed i128 inline. Larger immutable values share
their limb storage across assignments, argument snapshots and sign changes.
Bitwise updates copy shared limbs before writing, so other references retain
their original values. Remainders do not construct a discarded quotient, and
word-sized moduli use limb reduction with a precomputed reciprocal. Modular
powers with a 32-bit modulus use exact native products. Nonbinary input is
parsed in digit groups, while large decimal output splits into smaller blocks.
Large divisions split operands recursively instead of building a full reciprocal
for each new divisor. Long division leaves pack pairs of 32-bit limbs into
64-bit scratch words with exact 128-bit products; stored magnitudes retain their
32-bit representation. Long dividends can reuse exact reciprocal estimates and
bounded quotient corrections. Repeated divisors can retain that reciprocal in
their immutable magnitude; changing the magnitude invalidates the cache.
Equality and hashing depend only on the integer value. Smaller divisions retain
native word or long division arithmetic.
Identical immutable operand magnitudes use symmetric squaring. Short quotients
use upper divisor prefixes and one exact correction, reducing the work to the
quotient precision needed by a first division.
source_map retains original file, line and column. Its code field identifies
a lexical scope; instruction is a stable AST ordinal within that scope, rather
than a generated Rust instruction offset. These positions remain identical
with optional Rust helper pruning enabled or disabled.
A successful public result has backend="native". An unimplemented direct
lowering returns rust_source=None and an E006 diagnostic at the relevant
source operation. Official Python syntax, scope and module-resolution errors
keep their existing diagnostic categories.
TranspileOptions(optimize=False) and the CLI's --no-optimize option disable
optional Rust helper pruning. Direct typed generation and its correctness
proofs still run. Neither setting enables another execution path. --check
checks conversion without writing a Rust file.
The CLI and the web converter write compact Rust by default; the Python API
does so with TranspileOptions(compact=True), and the web bridge with the option
"compact": true. Compact output keeps the header
and every line break. It drops indentation and code comments, gives the
generator's own identifiers short names in their original naming style, and
moves repeated string literals into constants. It also removes local
declarations whose name is never used again in their block when the
initializer has no effect (a literal, None, a plain name or an empty struct),
turns write-only locals into let _ = value;, and drops unused Write trait
imports. Unused functions are already removed by helper pruning. If the program never reads an
exception's text (no except ... as name and no traceback or logging API),
builtin exception messages keep only their class name. Handlers still match
them, and an uncaught error still exits with status 1 and names its class.
--no-compact writes the readable form. Generated code builds with Rust
editions 2021 and 2024.
The converter uses Python's official ast and symtable APIs. Supported
bindings, operators and control flow become Rust values, expressions, loops
and functions. The current implementation covers proved integer and boolean
operations, shared immutable strings and f64 scalars, owned BigInt scalar operations, integer
lists and shared nested rows, dictionaries, sets and typed deques with
immutable scalar or tuple elements, including bounded queues. It supports
ordinary scalar functions with proved argument and return kinds, constant
defaults, positional and keyword binding, and calls between those functions.
Statically known function aliases retain their original definitions across
rebinding, with separate specializations for the actual argument kinds and
callable globals. Integer-list slices and sorted create independent lists.
Recursive functions use typed compiled frames. Finite source-function values
retain the selected definition across arguments, results, containers and
rebinding. Named nested functions capture typed environments belonging to each
enclosing invocation, including shared mutable values, nonlocal writes and
definition-time defaults. Escaping lambdas create a fresh function instance and
default values on each evaluation, including inside list comprehensions.
Repeated named nested definitions and cyclic closure ownership still require
implementation.
Python names can change type through distinct typed Rust slots. Compatible
branches and loops merge proved kinds; finite boolean/integer unions use a
small stack enum. ASCII string indexing accesses bytes directly. Opt-in Unicode
indexing caches character lengths and lazily builds shared byte offsets for
repeated reads. String snapshots share immutable storage, and proved fixed-width
ASCII loops can use guarded byte spans. Integer modes preserve their documented
wrapping policy.
Supported competitive-programming patterns include unpacked integer input,
list(map(int, input().split())), integer-list mutation and sorting, dictionary
aggregation, key deletion and insertion-order iteration, and owned adjacency-list BFS.
Standard input is buffered and read on demand. Output flushes before a blocking
input operation, including inside supported ordinary functions.
Resolved integer calls to math.gcd, lcm, isqrt, factorial, comb and
perm use native fixed-width arithmetic in i64/i128 mode, including results
larger than that width. Their mathematical result is normalized at the function
boundary. BigInt mode retains exact results. The module adapter for typed frames
is still being integrated.
Immediate iterator producers and consumers share immutable semantic plans.
for, reductions, list, sorted, next, unpacking, and string join consume
those plans, with callable identities and argument roles resolved before Rust
loop generation. Statically captured builtin aliases use the same producer and
consumer paths. Text and byte splitting share word-stream adapters; integer
parsing is selected from their proved element conversion, rather than from a
particular spelling of input().split(). Unpacking pulls at most one extra
converted item and assigns targets only after validating the item count.
In fixed-width modes, decimal text and byte conversions accumulate directly in
the selected Rust integer type. Scalar calls, captured builtin aliases, word
streams and proved character projections share this parser; they do not create
arbitrary-precision integer temporaries or acquire standard input solely to
convert an existing value. Unicode digit and whitespace data is included only
when the selected Unicode profile and retained operations require it.
Immediately consumed generator expressions use typed loops for reductions.
Retained generator expressions with one for clause use owned, typed Rust
iterator frames. Unpacking, filters, live lexical cells, shared cursors and
close() preserve creation versus pull timing. Nested clauses, async iteration
and injected send/throw protocols remain explicit native capability gaps.
All integer modes also support character-based string slicing,
strip/lstrip/rstrip, count, and join over proved string streams.
Ordinary class instances can use concrete Rust structs, typed fields and methods, and shared lists with proved scalar, tuple, instance or nested-list elements. Shallow copies and repetition retain inner aliases. Synchronous list comprehensions on this path generate typed loops with isolated target bindings. Small acyclic call paths use ordinary Result-returning Rust functions. Recursive methods and longer call chains use typed Rust futures with an iterative call executor and a logical Python recursion limit. Both call forms keep Python argument order and exception frames. Proved stable concrete fields can be reused lazily within loops without changing first-read errors. This initial class implementation has a separate proof boundary; integrating it with common semantic lowering remains required work. Multiple or dynamic inheritance, descriptors, metaclasses, escaped methods, cyclic ownership, heterogeneous mutable alternatives and unproved container protocols are not yet implemented.
If the implementation cannot establish a supported direct representation, it reports the missing construct or type combination. This currently includes many mutable aliases and mixed-type joins, remaining closure lifetime cases, exception handlers, user-defined generators, general object models, dynamic execution, and most standard-module calls. These are implementation gaps that must be restored through direct generation; they are not removed from the project's goals and do not require users to add type hints or rewrite ordinary Python as a substitute.
The source tree retains earlier general-runtime, object-model, parser and
execution code and its compatibility tests for the continuing rewrite. The
public transpile() and pytors entry points never call that backend after a
direct lowering fails. There is no fallback mode or switch that enables it.
The benchmarks check that CPython, generated Rust, and handwritten Rust produce the same results.
They cover arithmetic, I/O, indexed ASCII strings, arrays, sorting, dictionaries,
sets, BFS, DP, and BigInt.
Pass --pypy to include PyPy in the comparison; this requires pypy3 on PATH.
python3 benchmarks/run.py --all --output /tmp/bench.json --artifacts /tmp/bench-artifacts
python3 benchmarks/run.py --case arithmetic --case set --size 5000000 --output /tmp/selected.json
python3 benchmarks/run.py --all --size 17 --verify-onlyEach implementation repeats the same input, adjusting the repetition count to reduce the effect of process startup. The JSON report records median and raw execution times, peak RSS, transpilation and compilation times, source and executable sizes and hashes, and environment details. Checking the target of at most twice the runtime of handwritten Rust also requires checking startup overhead. If measurement limits prevent a sufficiently long run, the report records that limitation. Generated-source audit results are saved too, but text checks alone cannot prove the absence of unnecessary allocations or guarantee the performance of other programs.
Direct integer dictionaries and sets use Rust HashMap and HashSet.
Dictionary deletion selects reusable ordered slots, including inside ordinary
functions, preserving expected amortized O(1) updates and insertion order.
Operations at either end of a supported deque are amortized O(1).
Unimplemented benchmark patterns produce the same positioned diagnostic as
other input programs; they are not measured through another backend.
python3 tools/run_tests.py
python3 tests/test_native.py --benchmark-native
python3 tools/check_standalone.pytools/run_tests.py runs every tests/test*.py module in its own process, in
parallel (--jobs, one per CPU by default). --shard N --shards M selects one of
M size-balanced groups of modules; CI runs 8 such shards for each toolchain.
python3 -m unittest discover -s tests runs the same modules sequentially.
Tests include CPython differential checks, an independent fixed-width reference, randomized BigInt arithmetic, and explicit no-fallback API/CLI checks. Acceptance tests written for the earlier VM backend, which expected dynamic features that the native backend reports as positioned diagnostics, have been removed. CI targets Rust 1.85 and stable.
check_standalone.py converts one submission in every integer mode, builds
debug and optimized executables, and runs them without Python on PATH; the
output must equal CPython's. Its --wheel and --output options check a
packaged compiler and retain the generated sources, binaries and report.
The transpiler uses the MIT license. Its generated-output permission
allows original runtime helpers in generated programs to be distributed without
the project's copyright or MIT notice. Third-party code and data keep their own
required notices when included.
The license recorded for translated program logic defaults to CC0-1.0.
If the original Python source specifies a license, that license takes precedence.
The selected output license applies when the original source does not specify one.
Use --license or TranspileOptions(license=...) to select another bundled license.
List the available canonical identifiers with pytors --list-licenses:
pytors --list-licensesFor example:
pytors main.py -o main.rs --license CC0-1.0
pytors main.py -o main.rs --license Unlicense
pytors main.py -o main.rs --license MITLicense names are case-insensitive; cc0 is also accepted for CC0-1.0.
A source comment can override this choice, as shown above.
This selection applies to translated program logic. Original generated helpers
do not impose an additional project copyright notice. Third-party components
retain their required license notices when present.
Each generated Rust file begins with line comments containing the selected LICENSE,
the project URL, the exact statement “Transpilation does not use generative AI.”,
the integer and string modes, the original source's SHA-256 hash, and the full selected license text.
The original Python input, before import expansion, follows as line comments.
Generated implementation code omits explanatory and documentation comments.
Empty else blocks and unused scalar bindings are removed when their removal
preserves Rust type inference and Python execution order. Expressions that still
need evaluation keep their type context even when their result is discarded.
Objects with uncertain destructor or borrow lifetimes retain their bindings.
Required third-party attributions and license texts remain in a separate notice
block when their code or data is included.
Transpilation uses the compiler and runtime described above and does not call a generative-AI service.
See THIRD_PARTY.md and the bundled PSF and Unicode licenses for CPython-derived standard-library code, numerical algorithms, and Unicode data.