rustfy 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- rustfy-0.1.0/LICENSE +21 -0
- rustfy-0.1.0/PKG-INFO +151 -0
- rustfy-0.1.0/README.md +138 -0
- rustfy-0.1.0/pyproject.toml +26 -0
- rustfy-0.1.0/setup.cfg +4 -0
- rustfy-0.1.0/src/rustfy/__init__.py +179 -0
- rustfy-0.1.0/src/rustfy/__main__.py +3 -0
- rustfy-0.1.0/src/rustfy/_build.py +194 -0
- rustfy-0.1.0/src/rustfy/_compiler.py +413 -0
- rustfy-0.1.0/src/rustfy/_prelude.rs +137 -0
- rustfy-0.1.0/src/rustfy/cli.py +111 -0
- rustfy-0.1.0/src/rustfy.egg-info/PKG-INFO +151 -0
- rustfy-0.1.0/src/rustfy.egg-info/SOURCES.txt +15 -0
- rustfy-0.1.0/src/rustfy.egg-info/dependency_links.txt +1 -0
- rustfy-0.1.0/src/rustfy.egg-info/entry_points.txt +2 -0
- rustfy-0.1.0/src/rustfy.egg-info/top_level.txt +1 -0
- rustfy-0.1.0/tests/test_api.py +225 -0
rustfy-0.1.0/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Erick Cassoli
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
rustfy-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: rustfy
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Compile typed Python loops to Rust with a decorator and optional shadow checks.
|
|
5
|
+
License-Expression: MIT
|
|
6
|
+
Project-URL: Repository, https://github.com/ErickCassoli/rustfy
|
|
7
|
+
Project-URL: Issues, https://github.com/ErickCassoli/rustfy/issues
|
|
8
|
+
Keywords: rust,pyo3,python,ast,jit
|
|
9
|
+
Requires-Python: >=3.10
|
|
10
|
+
Description-Content-Type: text/markdown
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Dynamic: license-file
|
|
13
|
+
|
|
14
|
+
# Rustfy
|
|
15
|
+
|
|
16
|
+
Rustfy turns typed numeric Python functions into Rust extensions on the first call.
|
|
17
|
+
Add a decorator, keep calling the function from Python, and reuse the compiled
|
|
18
|
+
module across processes.
|
|
19
|
+
|
|
20
|
+
## Install
|
|
21
|
+
|
|
22
|
+
Use CPython 3.10–3.14 with the GIL, Cargo, and a native linker. On Windows x64,
|
|
23
|
+
use the Rust MSVC toolchain and Visual Studio C++ Build Tools.
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
git clone https://github.com/ErickCassoli/rustfy.git
|
|
27
|
+
cd rustfy
|
|
28
|
+
python -m pip install .
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
Save decorated functions in a .py file so Rustfy can read their source.
|
|
32
|
+
|
|
33
|
+
```python
|
|
34
|
+
from rustfy import rustfy
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
@rustfy(verify=True)
|
|
38
|
+
def total_energy(samples: list[float]) -> float:
|
|
39
|
+
total = 0.0
|
|
40
|
+
for i in range(len(samples)):
|
|
41
|
+
total += samples[i] * samples[i]
|
|
42
|
+
return total
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
print(total_energy([1.0, 2.0, 3.0])) # 14.0
|
|
46
|
+
print(total_energy.rustfy_info())
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
`rustify` is an alias for `rustfy`. Both support `@rustfy` and
|
|
50
|
+
`@rustfy(verify=True)`. The first call blocks while Cargo builds the extension
|
|
51
|
+
in release mode. Later calls reuse the extension, including in a new process.
|
|
52
|
+
|
|
53
|
+
## Native subset
|
|
54
|
+
|
|
55
|
+
- Synchronous, pure functions with parameter and return annotations. Positional
|
|
56
|
+
arguments, keyword arguments, and Python defaults are supported.
|
|
57
|
+
- Exact `int` values in the signed 64-bit range, `float`, `bool`, and one-dimensional
|
|
58
|
+
`list[float]` or `list[int]` with exact element types. Inputs are read-only.
|
|
59
|
+
A function can allocate an annotated empty list, append to it, assign its
|
|
60
|
+
elements, and return it.
|
|
61
|
+
- Scalar assignments, augmented arithmetic assignments, indexing (including
|
|
62
|
+
negative indices), `for ... in range(...)`, `while`, `break`, `continue`,
|
|
63
|
+
`if`/`elif`/`else`, conditional expressions, and boolean operations.
|
|
64
|
+
- `+`, `-`, `*`, `/`, `**`, integer `//` and `%`, ordinary comparisons,
|
|
65
|
+
and standard `len`, `math.sqrt`, `abs`, `min`, `max`, and two-argument
|
|
66
|
+
`pow`. The supported `min`/`max` form takes two or more scalars of a single
|
|
67
|
+
type. Locals keep the type of their first assignment.
|
|
68
|
+
|
|
69
|
+
Rustfy falls back to the original Python function on unsupported syntax,
|
|
70
|
+
non-native inputs, overflow, out-of-bounds indexing, or an operation outside
|
|
71
|
+
the native numeric contract. It preserves the original result or exception.
|
|
72
|
+
Unsupported syntax and build or load failures disable native execution for the
|
|
73
|
+
decorated function. A call-specific numeric or input failure uses Python for
|
|
74
|
+
that call. Read `rustfy_info()` for the backend, latest reason, fallback count,
|
|
75
|
+
cache hit, build time, and comparison count.
|
|
76
|
+
|
|
77
|
+
With `verify=True`, the first three successful native calls also run the
|
|
78
|
+
original Python function. Integers and booleans compare exactly, floats use
|
|
79
|
+
`math.isclose` with `rel_tol=1e-9` and `abs_tol=1e-12`, and lists compare
|
|
80
|
+
element by element. Same-sign infinities match. NaNs fail the check. A
|
|
81
|
+
mismatch returns the Python result and disables Rust for that decorated
|
|
82
|
+
function. Functions should be pure and their inputs should stay stable
|
|
83
|
+
throughout the call.
|
|
84
|
+
|
|
85
|
+
## Build cache
|
|
86
|
+
|
|
87
|
+
Entries live in `~/.cache/rustfy/<sha256>/`. The key includes the normalized AST
|
|
88
|
+
and signature, generator and native source, platform, architecture, and Python
|
|
89
|
+
extension compatibility. Generated Rust is under `src/lib.rs` in each entry.
|
|
90
|
+
On Windows the extension is a `.pyd`. On Linux and macOS it is a `.so`.
|
|
91
|
+
|
|
92
|
+
Set `RUSTFY_CACHE_DIR` to use another cache, or `RUSTFY_CARGO` to select a Cargo
|
|
93
|
+
executable. The first build normally fetches dependencies from the Cargo
|
|
94
|
+
registry. With the dependencies cached, set `CARGO_NET_OFFLINE=true` for an
|
|
95
|
+
offline build. See the [PyO3 build guide](https://pyo3.rs/v0.27.2/building-and-distribution.html#manual-builds)
|
|
96
|
+
for platform requirements.
|
|
97
|
+
|
|
98
|
+
## Benchmarks
|
|
99
|
+
|
|
100
|
+
```sh
|
|
101
|
+
rustfy bench benchmarks/moving_average.py
|
|
102
|
+
rustfy bench benchmarks/levenshtein.py
|
|
103
|
+
rustfy bench benchmarks/simulation.py
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
Windows 11 Pro build 26200, AMD Ryzen 7 5700X, CPython 3.14.3 x64, Cargo and
|
|
107
|
+
rustc 1.100.1. The table reports the median of five warm calls per backend on
|
|
108
|
+
identical inputs. Rust timings include PyO3 argument and result conversion.
|
|
109
|
+
The CLI reports build and the combined cost of three Python–Rust comparisons
|
|
110
|
+
separately. Cargo's local dependency registry was populated before this offline run.
|
|
111
|
+
The first build started with a fresh Cargo target directory, which the next
|
|
112
|
+
two builds reused.
|
|
113
|
+
|
|
114
|
+
| Workload | Size | Python (ms) | Rust (ms) | Speedup | Matches |
|
|
115
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
116
|
+
| 100-period trailing mean | 2,000 closes | 7.969 | 0.212 | 37.54× | 3/3 |
|
|
117
|
+
| 100-period trailing mean | 1,000,000 closes | 3,882.301 | 118.993 | **32.63×** | 3/3 |
|
|
118
|
+
| Levenshtein | 120 code points per string | 2.102 | 0.025 | 82.74× | 3/3 |
|
|
119
|
+
| Levenshtein | 1,600 code points per string | 491.775 | 3.612 | **136.14×** | 3/3 |
|
|
120
|
+
| Damped oscillator simulation | 64 trajectories | 0.595 | 0.030 | 19.58× | 3/3 |
|
|
121
|
+
| Damped oscillator simulation | 12,000 trajectories | 119.854 | 5.433 | **22.06×** | 3/3 |
|
|
122
|
+
|
|
123
|
+
Initial extension builds took 13.652 s, 1.029 s, and 0.997 s in the order
|
|
124
|
+
shown. The smallest measured size with a faster native call was 2,000
|
|
125
|
+
closes, 120 code points, and 64 trajectories, respectively.
|
|
126
|
+
|
|
127
|
+
- The trailing mean directly sums each 100-price window using seeded synthetic
|
|
128
|
+
candle closes. The first result aligns with the 100th close. Each output uses
|
|
129
|
+
only the current and preceding closes. Both backends run the same direct
|
|
130
|
+
window algorithm.
|
|
131
|
+
- The Levenshtein example computes edit distance with one scratch row on
|
|
132
|
+
pre-encoded Unicode code points. Encoding happens before either timer.
|
|
133
|
+
- The simulation advances each seeded initial position through 96 symplectic
|
|
134
|
+
Euler steps at `dt=0.01` and returns the mean final energy.
|
|
135
|
+
|
|
136
|
+
For a custom benchmark, set `BENCHMARK` in your script to a decorated function.
|
|
137
|
+
Define `benchmark_cases()` to yield pairs of `(size, positional_args)`. The CLI
|
|
138
|
+
runs the script and measures each size with the same arguments for both
|
|
139
|
+
implementations. Use `--repeats` to set the number of timed calls.
|
|
140
|
+
|
|
141
|
+
## Tests
|
|
142
|
+
|
|
143
|
+
```sh
|
|
144
|
+
python -m unittest discover -s tests -v
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
The GitHub Actions matrix builds and imports native extensions on Windows,
|
|
148
|
+
Ubuntu, and macOS. The suite checks cache reuse in a new process, Python
|
|
149
|
+
fallbacks, and the benchmark CLI.
|
|
150
|
+
|
|
151
|
+
[MIT License](LICENSE)
|
rustfy-0.1.0/README.md
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
1
|
+
# Rustfy
|
|
2
|
+
|
|
3
|
+
Rustfy turns typed numeric Python functions into Rust extensions on the first call.
|
|
4
|
+
Add a decorator, keep calling the function from Python, and reuse the compiled
|
|
5
|
+
module across processes.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
Use CPython 3.10–3.14 with the GIL, Cargo, and a native linker. On Windows x64,
|
|
10
|
+
use the Rust MSVC toolchain and Visual Studio C++ Build Tools.
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
git clone https://github.com/ErickCassoli/rustfy.git
|
|
14
|
+
cd rustfy
|
|
15
|
+
python -m pip install .
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
Save decorated functions in a .py file so Rustfy can read their source.
|
|
19
|
+
|
|
20
|
+
```python
|
|
21
|
+
from rustfy import rustfy
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@rustfy(verify=True)
|
|
25
|
+
def total_energy(samples: list[float]) -> float:
|
|
26
|
+
total = 0.0
|
|
27
|
+
for i in range(len(samples)):
|
|
28
|
+
total += samples[i] * samples[i]
|
|
29
|
+
return total
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
print(total_energy([1.0, 2.0, 3.0])) # 14.0
|
|
33
|
+
print(total_energy.rustfy_info())
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
`rustify` is an alias for `rustfy`. Both support `@rustfy` and
|
|
37
|
+
`@rustfy(verify=True)`. The first call blocks while Cargo builds the extension
|
|
38
|
+
in release mode. Later calls reuse the extension, including in a new process.
|
|
39
|
+
|
|
40
|
+
## Native subset
|
|
41
|
+
|
|
42
|
+
- Synchronous, pure functions with parameter and return annotations. Positional
|
|
43
|
+
arguments, keyword arguments, and Python defaults are supported.
|
|
44
|
+
- Exact `int` values in the signed 64-bit range, `float`, `bool`, and one-dimensional
|
|
45
|
+
`list[float]` or `list[int]` with exact element types. Inputs are read-only.
|
|
46
|
+
A function can allocate an annotated empty list, append to it, assign its
|
|
47
|
+
elements, and return it.
|
|
48
|
+
- Scalar assignments, augmented arithmetic assignments, indexing (including
|
|
49
|
+
negative indices), `for ... in range(...)`, `while`, `break`, `continue`,
|
|
50
|
+
`if`/`elif`/`else`, conditional expressions, and boolean operations.
|
|
51
|
+
- `+`, `-`, `*`, `/`, `**`, integer `//` and `%`, ordinary comparisons,
|
|
52
|
+
and standard `len`, `math.sqrt`, `abs`, `min`, `max`, and two-argument
|
|
53
|
+
`pow`. The supported `min`/`max` form takes two or more scalars of a single
|
|
54
|
+
type. Locals keep the type of their first assignment.
|
|
55
|
+
|
|
56
|
+
Rustfy falls back to the original Python function on unsupported syntax,
|
|
57
|
+
non-native inputs, overflow, out-of-bounds indexing, or an operation outside
|
|
58
|
+
the native numeric contract. It preserves the original result or exception.
|
|
59
|
+
Unsupported syntax and build or load failures disable native execution for the
|
|
60
|
+
decorated function. A call-specific numeric or input failure uses Python for
|
|
61
|
+
that call. Read `rustfy_info()` for the backend, latest reason, fallback count,
|
|
62
|
+
cache hit, build time, and comparison count.
|
|
63
|
+
|
|
64
|
+
With `verify=True`, the first three successful native calls also run the
|
|
65
|
+
original Python function. Integers and booleans compare exactly, floats use
|
|
66
|
+
`math.isclose` with `rel_tol=1e-9` and `abs_tol=1e-12`, and lists compare
|
|
67
|
+
element by element. Same-sign infinities match. NaNs fail the check. A
|
|
68
|
+
mismatch returns the Python result and disables Rust for that decorated
|
|
69
|
+
function. Functions should be pure and their inputs should stay stable
|
|
70
|
+
throughout the call.
|
|
71
|
+
|
|
72
|
+
## Build cache
|
|
73
|
+
|
|
74
|
+
Entries live in `~/.cache/rustfy/<sha256>/`. The key includes the normalized AST
|
|
75
|
+
and signature, generator and native source, platform, architecture, and Python
|
|
76
|
+
extension compatibility. Generated Rust is under `src/lib.rs` in each entry.
|
|
77
|
+
On Windows the extension is a `.pyd`. On Linux and macOS it is a `.so`.
|
|
78
|
+
|
|
79
|
+
Set `RUSTFY_CACHE_DIR` to use another cache, or `RUSTFY_CARGO` to select a Cargo
|
|
80
|
+
executable. The first build normally fetches dependencies from the Cargo
|
|
81
|
+
registry. With the dependencies cached, set `CARGO_NET_OFFLINE=true` for an
|
|
82
|
+
offline build. See the [PyO3 build guide](https://pyo3.rs/v0.27.2/building-and-distribution.html#manual-builds)
|
|
83
|
+
for platform requirements.
|
|
84
|
+
|
|
85
|
+
## Benchmarks
|
|
86
|
+
|
|
87
|
+
```sh
|
|
88
|
+
rustfy bench benchmarks/moving_average.py
|
|
89
|
+
rustfy bench benchmarks/levenshtein.py
|
|
90
|
+
rustfy bench benchmarks/simulation.py
|
|
91
|
+
```
|
|
92
|
+
|
|
93
|
+
Windows 11 Pro build 26200, AMD Ryzen 7 5700X, CPython 3.14.3 x64, Cargo and
|
|
94
|
+
rustc 1.100.1. The table reports the median of five warm calls per backend on
|
|
95
|
+
identical inputs. Rust timings include PyO3 argument and result conversion.
|
|
96
|
+
The CLI reports build and the combined cost of three Python–Rust comparisons
|
|
97
|
+
separately. Cargo's local dependency registry was populated before this offline run.
|
|
98
|
+
The first build started with a fresh Cargo target directory, which the next
|
|
99
|
+
two builds reused.
|
|
100
|
+
|
|
101
|
+
| Workload | Size | Python (ms) | Rust (ms) | Speedup | Matches |
|
|
102
|
+
| --- | ---: | ---: | ---: | ---: | ---: |
|
|
103
|
+
| 100-period trailing mean | 2,000 closes | 7.969 | 0.212 | 37.54× | 3/3 |
|
|
104
|
+
| 100-period trailing mean | 1,000,000 closes | 3,882.301 | 118.993 | **32.63×** | 3/3 |
|
|
105
|
+
| Levenshtein | 120 code points per string | 2.102 | 0.025 | 82.74× | 3/3 |
|
|
106
|
+
| Levenshtein | 1,600 code points per string | 491.775 | 3.612 | **136.14×** | 3/3 |
|
|
107
|
+
| Damped oscillator simulation | 64 trajectories | 0.595 | 0.030 | 19.58× | 3/3 |
|
|
108
|
+
| Damped oscillator simulation | 12,000 trajectories | 119.854 | 5.433 | **22.06×** | 3/3 |
|
|
109
|
+
|
|
110
|
+
Initial extension builds took 13.652 s, 1.029 s, and 0.997 s in the order
|
|
111
|
+
shown. The smallest measured size with a faster native call was 2,000
|
|
112
|
+
closes, 120 code points, and 64 trajectories, respectively.
|
|
113
|
+
|
|
114
|
+
- The trailing mean directly sums each 100-price window using seeded synthetic
|
|
115
|
+
candle closes. The first result aligns with the 100th close. Each output uses
|
|
116
|
+
only the current and preceding closes. Both backends run the same direct
|
|
117
|
+
window algorithm.
|
|
118
|
+
- The Levenshtein example computes edit distance with one scratch row on
|
|
119
|
+
pre-encoded Unicode code points. Encoding happens before either timer.
|
|
120
|
+
- The simulation advances each seeded initial position through 96 symplectic
|
|
121
|
+
Euler steps at `dt=0.01` and returns the mean final energy.
|
|
122
|
+
|
|
123
|
+
For a custom benchmark, set `BENCHMARK` in your script to a decorated function.
|
|
124
|
+
Define `benchmark_cases()` to yield pairs of `(size, positional_args)`. The CLI
|
|
125
|
+
runs the script and measures each size with the same arguments for both
|
|
126
|
+
implementations. Use `--repeats` to set the number of timed calls.
|
|
127
|
+
|
|
128
|
+
## Tests
|
|
129
|
+
|
|
130
|
+
```sh
|
|
131
|
+
python -m unittest discover -s tests -v
|
|
132
|
+
```
|
|
133
|
+
|
|
134
|
+
The GitHub Actions matrix builds and imports native extensions on Windows,
|
|
135
|
+
Ubuntu, and macOS. The suite checks cache reuse in a new process, Python
|
|
136
|
+
fallbacks, and the benchmark CLI.
|
|
137
|
+
|
|
138
|
+
[MIT License](LICENSE)
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=77"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "rustfy"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Compile typed Python loops to Rust with a decorator and optional shadow checks."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "MIT"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
keywords = ["rust", "pyo3", "python", "ast", "jit"]
|
|
14
|
+
|
|
15
|
+
[project.urls]
|
|
16
|
+
Repository = "https://github.com/ErickCassoli/rustfy"
|
|
17
|
+
Issues = "https://github.com/ErickCassoli/rustfy/issues"
|
|
18
|
+
|
|
19
|
+
[project.scripts]
|
|
20
|
+
rustfy = "rustfy.cli:main"
|
|
21
|
+
|
|
22
|
+
[tool.setuptools.packages.find]
|
|
23
|
+
where = ["src"]
|
|
24
|
+
|
|
25
|
+
[tool.setuptools.package-data]
|
|
26
|
+
rustfy = ["_prelude.rs"]
|
rustfy-0.1.0/setup.cfg
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
"""Compile typed numeric Python functions on demand with Rust and PyO3."""
|
|
2
|
+
|
|
3
|
+
from dataclasses import dataclass
|
|
4
|
+
from functools import wraps
|
|
5
|
+
import inspect
|
|
6
|
+
import math
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
import sys
|
|
9
|
+
import sysconfig
|
|
10
|
+
from threading import RLock
|
|
11
|
+
|
|
12
|
+
from . import _build
|
|
13
|
+
from ._compiler import Unsupported, compile_function
|
|
14
|
+
|
|
15
|
+
__all__ = ["RustfyInfo", "rustfy", "rustify"]
|
|
16
|
+
|
|
17
|
+
_REL_TOL = 1e-9
|
|
18
|
+
_ABS_TOL = 1e-12
|
|
19
|
+
_CHECKS = 3
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
@dataclass(frozen=True)
|
|
23
|
+
class RustfyInfo:
|
|
24
|
+
"""A snapshot of the active backend and its most recent diagnostic."""
|
|
25
|
+
|
|
26
|
+
backend: str
|
|
27
|
+
reason: str | None
|
|
28
|
+
checks: int
|
|
29
|
+
matches: int
|
|
30
|
+
fallbacks: int
|
|
31
|
+
artifact: Path | None
|
|
32
|
+
cache_hit: bool | None
|
|
33
|
+
build_seconds: float
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _equivalent(python, rust):
|
|
37
|
+
kind = type(python)
|
|
38
|
+
if kind is not type(rust):
|
|
39
|
+
return False
|
|
40
|
+
if kind is float:
|
|
41
|
+
return math.isclose(python, rust, rel_tol=_REL_TOL, abs_tol=_ABS_TOL)
|
|
42
|
+
if kind in (int, bool):
|
|
43
|
+
return python == rust
|
|
44
|
+
if kind is list:
|
|
45
|
+
return len(python) == len(rust) and all(_equivalent(a, b) for a, b in zip(python, rust))
|
|
46
|
+
return False
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class _Runner:
|
|
50
|
+
def __init__(self, function, verify):
|
|
51
|
+
self.function = function
|
|
52
|
+
self.verify = verify
|
|
53
|
+
self.lock = RLock()
|
|
54
|
+
self.program = None
|
|
55
|
+
self.native = None
|
|
56
|
+
self.attempted = False
|
|
57
|
+
self.disabled = False
|
|
58
|
+
self.reason = None
|
|
59
|
+
self.checks = 0
|
|
60
|
+
self.matches = 0
|
|
61
|
+
self.fallbacks = 0
|
|
62
|
+
|
|
63
|
+
def prepare(self):
|
|
64
|
+
if self.attempted:
|
|
65
|
+
return
|
|
66
|
+
self.attempted = True
|
|
67
|
+
try:
|
|
68
|
+
if sys.implementation.name != "cpython" or sysconfig.get_config_var("Py_GIL_DISABLED"):
|
|
69
|
+
raise Unsupported("the native backend requires CPython with the GIL")
|
|
70
|
+
if getattr(self.function, "__signature__", None) is not None:
|
|
71
|
+
raise Unsupported("custom Python signatures")
|
|
72
|
+
self.program = compile_function(self.function)
|
|
73
|
+
self.code = self.function.__code__
|
|
74
|
+
signature = inspect.signature(self.function, follow_wrapped=False)
|
|
75
|
+
self.positional_count = len(signature.parameters)
|
|
76
|
+
self.has_keyword_only = any(
|
|
77
|
+
parameter.kind is parameter.KEYWORD_ONLY for parameter in signature.parameters.values()
|
|
78
|
+
)
|
|
79
|
+
except (Unsupported, OSError, SyntaxError, TypeError, RecursionError) as error:
|
|
80
|
+
self.reason = f"unsupported: {error}"
|
|
81
|
+
return
|
|
82
|
+
|
|
83
|
+
try:
|
|
84
|
+
self.native = _build.prepare(self.program)
|
|
85
|
+
except _build.BuildError as error:
|
|
86
|
+
self.reason = str(error)
|
|
87
|
+
except Exception as error:
|
|
88
|
+
self.reason = f"native setup failed: {error}"
|
|
89
|
+
|
|
90
|
+
def call_native(self, args, kwargs):
|
|
91
|
+
if self.native is None or self.disabled:
|
|
92
|
+
raise RuntimeError(self.reason or "native backend is unavailable")
|
|
93
|
+
if (
|
|
94
|
+
self.function.__code__ is not self.code
|
|
95
|
+
or getattr(self.function, "__signature__", None) is not None
|
|
96
|
+
or not self.program.bindings_match(self.function)
|
|
97
|
+
):
|
|
98
|
+
raise ValueError("Python function, signature, or builtin bindings changed")
|
|
99
|
+
|
|
100
|
+
if not kwargs and not self.has_keyword_only and len(args) == self.positional_count:
|
|
101
|
+
values = args
|
|
102
|
+
else:
|
|
103
|
+
# Python defaults can change after decoration.
|
|
104
|
+
signature = inspect.signature(self.function, follow_wrapped=False)
|
|
105
|
+
bound = signature.bind(*args, **kwargs)
|
|
106
|
+
bound.apply_defaults()
|
|
107
|
+
values = tuple(bound.arguments.values())
|
|
108
|
+
return self.native.function(*values)
|
|
109
|
+
|
|
110
|
+
def compare(self, python, rust):
|
|
111
|
+
self.checks += 1
|
|
112
|
+
if _equivalent(python, rust):
|
|
113
|
+
self.matches += 1
|
|
114
|
+
return True
|
|
115
|
+
self.disabled = True
|
|
116
|
+
self.reason = "verification mismatch between Python and Rust"
|
|
117
|
+
return False
|
|
118
|
+
|
|
119
|
+
def __call__(self, *args, **kwargs):
|
|
120
|
+
with self.lock:
|
|
121
|
+
self.prepare()
|
|
122
|
+
if self.native is not None and not self.disabled:
|
|
123
|
+
try:
|
|
124
|
+
rust = self.call_native(args, kwargs)
|
|
125
|
+
except Exception as error:
|
|
126
|
+
self.reason = f"native call fell back: {type(error).__name__}: {error}"
|
|
127
|
+
else:
|
|
128
|
+
if not self.verify or self.checks >= _CHECKS:
|
|
129
|
+
return rust
|
|
130
|
+
try:
|
|
131
|
+
python = self.function(*args, **kwargs)
|
|
132
|
+
except Exception:
|
|
133
|
+
self.disabled = True
|
|
134
|
+
self.reason = "verification mismatch: the Python function raised an exception"
|
|
135
|
+
self.checks += 1
|
|
136
|
+
self.fallbacks += 1
|
|
137
|
+
raise
|
|
138
|
+
if self.compare(python, rust):
|
|
139
|
+
return rust
|
|
140
|
+
self.fallbacks += 1
|
|
141
|
+
return python
|
|
142
|
+
self.fallbacks += 1
|
|
143
|
+
return self.function(*args, **kwargs)
|
|
144
|
+
|
|
145
|
+
def info(self):
|
|
146
|
+
with self.lock:
|
|
147
|
+
native = self.native
|
|
148
|
+
return RustfyInfo(
|
|
149
|
+
backend="pending" if not self.attempted else "rust" if native and not self.disabled else "python",
|
|
150
|
+
reason=self.reason,
|
|
151
|
+
checks=self.checks,
|
|
152
|
+
matches=self.matches,
|
|
153
|
+
fallbacks=self.fallbacks,
|
|
154
|
+
artifact=native.artifact if native else None,
|
|
155
|
+
cache_hit=native.cache_hit if native else None,
|
|
156
|
+
build_seconds=native.build_seconds if native else 0.0,
|
|
157
|
+
)
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def rustfy(function=None, *, verify=False):
|
|
161
|
+
"""Decorate a pure, typed numeric function; unsupported calls run in Python."""
|
|
162
|
+
|
|
163
|
+
def decorate(original):
|
|
164
|
+
runner = _Runner(original, verify)
|
|
165
|
+
|
|
166
|
+
@wraps(original)
|
|
167
|
+
def wrapped(*args, **kwargs):
|
|
168
|
+
return runner(*args, **kwargs)
|
|
169
|
+
|
|
170
|
+
wrapped.rustfy_info = runner.info
|
|
171
|
+
wrapped._rustfy_runner = runner
|
|
172
|
+
return wrapped
|
|
173
|
+
|
|
174
|
+
if function is None:
|
|
175
|
+
return decorate
|
|
176
|
+
return decorate(function)
|
|
177
|
+
|
|
178
|
+
|
|
179
|
+
rustify = rustfy
|