rustfy 0.1.0__py3-none-any.whl
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/__init__.py +179 -0
- rustfy/__main__.py +3 -0
- rustfy/_build.py +194 -0
- rustfy/_compiler.py +413 -0
- rustfy/_prelude.rs +137 -0
- rustfy/cli.py +111 -0
- rustfy-0.1.0.dist-info/METADATA +151 -0
- rustfy-0.1.0.dist-info/RECORD +12 -0
- rustfy-0.1.0.dist-info/WHEEL +5 -0
- rustfy-0.1.0.dist-info/entry_points.txt +2 -0
- rustfy-0.1.0.dist-info/licenses/LICENSE +21 -0
- rustfy-0.1.0.dist-info/top_level.txt +1 -0
rustfy/__init__.py
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
|
rustfy/__main__.py
ADDED
rustfy/_build.py
ADDED
|
@@ -0,0 +1,194 @@
|
|
|
1
|
+
"""Build and import native modules from a per-user content-addressed cache."""
|
|
2
|
+
|
|
3
|
+
from contextlib import contextmanager
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import hashlib
|
|
6
|
+
import importlib.util
|
|
7
|
+
import json
|
|
8
|
+
import os
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
import platform
|
|
11
|
+
import shutil
|
|
12
|
+
import struct
|
|
13
|
+
import subprocess
|
|
14
|
+
import sys
|
|
15
|
+
import sysconfig
|
|
16
|
+
import tempfile
|
|
17
|
+
from time import monotonic, perf_counter, sleep
|
|
18
|
+
from typing import Callable
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
_MANIFEST = """\
|
|
22
|
+
[package]
|
|
23
|
+
name = "rustfy-generated"
|
|
24
|
+
version = "0.1.0"
|
|
25
|
+
edition = "2021"
|
|
26
|
+
|
|
27
|
+
[lib]
|
|
28
|
+
name = "RUSTFY_MODULE"
|
|
29
|
+
crate-type = ["cdylib"]
|
|
30
|
+
|
|
31
|
+
[dependencies]
|
|
32
|
+
pyo3 = { version = "=0.27.2", features = ["extension-module"] }
|
|
33
|
+
|
|
34
|
+
[build-dependencies]
|
|
35
|
+
pyo3-build-config = "=0.27.2"
|
|
36
|
+
"""
|
|
37
|
+
_BUILD_RS = """\
|
|
38
|
+
fn main() {
|
|
39
|
+
pyo3_build_config::add_extension_module_link_args();
|
|
40
|
+
}
|
|
41
|
+
"""
|
|
42
|
+
_PRELUDE = Path(__file__).with_name("_prelude.rs")
|
|
43
|
+
_BUILD_TIMEOUT = 300
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
class BuildError(RuntimeError):
|
|
47
|
+
pass
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
@dataclass(frozen=True)
|
|
51
|
+
class Native:
|
|
52
|
+
function: Callable
|
|
53
|
+
artifact: Path
|
|
54
|
+
cache_hit: bool
|
|
55
|
+
build_seconds: float
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _cache_root():
|
|
59
|
+
directory = os.environ.get("RUSTFY_CACHE_DIR")
|
|
60
|
+
return Path(directory or Path.home() / ".cache" / "rustfy").expanduser().resolve()
|
|
61
|
+
|
|
62
|
+
|
|
63
|
+
def _key(program, prelude, extension):
|
|
64
|
+
identity = [
|
|
65
|
+
"rustfy-0.1.0",
|
|
66
|
+
program.ast_key,
|
|
67
|
+
program.rust,
|
|
68
|
+
prelude,
|
|
69
|
+
_MANIFEST,
|
|
70
|
+
_BUILD_RS,
|
|
71
|
+
sys.implementation.cache_tag,
|
|
72
|
+
sysconfig.get_config_var("SOABI"),
|
|
73
|
+
extension,
|
|
74
|
+
sys.platform,
|
|
75
|
+
platform.machine(),
|
|
76
|
+
struct.calcsize("P"),
|
|
77
|
+
]
|
|
78
|
+
data = json.dumps(identity, ensure_ascii=True, separators=(",", ":")).encode("ascii")
|
|
79
|
+
return hashlib.sha256(data).hexdigest()
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
@contextmanager
|
|
83
|
+
def _lock(path):
|
|
84
|
+
# The OS releases the lock when the owning process exits, including on a crash.
|
|
85
|
+
with path.open("a+b") as file:
|
|
86
|
+
if os.name == "nt":
|
|
87
|
+
import msvcrt
|
|
88
|
+
|
|
89
|
+
file.seek(0)
|
|
90
|
+
deadline = monotonic() + _BUILD_TIMEOUT + 15
|
|
91
|
+
while True:
|
|
92
|
+
try:
|
|
93
|
+
msvcrt.locking(file.fileno(), msvcrt.LK_NBLCK, 1)
|
|
94
|
+
break
|
|
95
|
+
except OSError as error:
|
|
96
|
+
if monotonic() >= deadline:
|
|
97
|
+
raise BuildError("timed out waiting for the cache entry") from error
|
|
98
|
+
sleep(0.1)
|
|
99
|
+
try:
|
|
100
|
+
yield
|
|
101
|
+
finally:
|
|
102
|
+
msvcrt.locking(file.fileno(), msvcrt.LK_UNLCK, 1)
|
|
103
|
+
else:
|
|
104
|
+
import fcntl
|
|
105
|
+
|
|
106
|
+
fcntl.flock(file, fcntl.LOCK_EX)
|
|
107
|
+
yield
|
|
108
|
+
|
|
109
|
+
|
|
110
|
+
def _cargo():
|
|
111
|
+
override = os.environ.get("RUSTFY_CARGO")
|
|
112
|
+
if override:
|
|
113
|
+
return override
|
|
114
|
+
name = "cargo.exe" if os.name == "nt" else "cargo"
|
|
115
|
+
return shutil.which(name) or str(Path.home() / ".cargo" / "bin" / name)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _build(staging, target_dir, module, source):
|
|
119
|
+
(staging / "src").mkdir()
|
|
120
|
+
(staging / "src" / "lib.rs").write_text(source, encoding="utf-8")
|
|
121
|
+
(staging / "Cargo.toml").write_text(_MANIFEST.replace("RUSTFY_MODULE", module), encoding="utf-8")
|
|
122
|
+
(staging / "build.rs").write_text(_BUILD_RS, encoding="utf-8")
|
|
123
|
+
|
|
124
|
+
command = [
|
|
125
|
+
_cargo(), "build", "--release", "-j", "10", "--target-dir", str(target_dir),
|
|
126
|
+
"--message-format=json-render-diagnostics",
|
|
127
|
+
]
|
|
128
|
+
env = dict(os.environ, PYO3_PYTHON=sys.executable)
|
|
129
|
+
try:
|
|
130
|
+
result = subprocess.run(
|
|
131
|
+
command, cwd=staging, env=env, capture_output=True, text=True, encoding="utf-8",
|
|
132
|
+
errors="replace", timeout=_BUILD_TIMEOUT, check=False,
|
|
133
|
+
)
|
|
134
|
+
except (OSError, subprocess.TimeoutExpired) as error:
|
|
135
|
+
raise BuildError(f"build failed: {error}") from error
|
|
136
|
+
if result.returncode:
|
|
137
|
+
detail = "\n".join(result.stderr.strip().splitlines()[-12:])
|
|
138
|
+
raise BuildError(f"build failed (Cargo exit {result.returncode}): {detail}")
|
|
139
|
+
|
|
140
|
+
for line in result.stdout.splitlines():
|
|
141
|
+
message = json.loads(line)
|
|
142
|
+
if message.get("reason") != "compiler-artifact" or message["target"]["name"] != module:
|
|
143
|
+
continue
|
|
144
|
+
for name in message["filenames"]:
|
|
145
|
+
path = Path(name)
|
|
146
|
+
if path.suffix in {".dll", ".so", ".dylib"}:
|
|
147
|
+
return path
|
|
148
|
+
raise BuildError("build failed: Cargo did not produce a native extension")
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def _load(module, artifact):
|
|
152
|
+
spec = importlib.util.spec_from_file_location(module, artifact)
|
|
153
|
+
if spec is None or spec.loader is None:
|
|
154
|
+
raise ImportError(f"no loader for {artifact.name}")
|
|
155
|
+
extension = importlib.util.module_from_spec(spec)
|
|
156
|
+
spec.loader.exec_module(extension)
|
|
157
|
+
return extension.run
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def prepare(program):
|
|
161
|
+
extension = sysconfig.get_config_var("EXT_SUFFIX")
|
|
162
|
+
if not extension:
|
|
163
|
+
raise BuildError("Python has no native extension suffix")
|
|
164
|
+
prelude = _PRELUDE.read_text(encoding="utf-8")
|
|
165
|
+
key = _key(program, prelude, extension)
|
|
166
|
+
module = f"rf_{key[:32]}"
|
|
167
|
+
root = _cache_root()
|
|
168
|
+
root.mkdir(parents=True, exist_ok=True, mode=0o700)
|
|
169
|
+
entry = root / key
|
|
170
|
+
artifact = entry / f"{module}{extension}"
|
|
171
|
+
build_seconds = 0.0
|
|
172
|
+
|
|
173
|
+
cache_hit = artifact.is_file()
|
|
174
|
+
if not cache_hit:
|
|
175
|
+
with _lock(root / f".{key}.lock"):
|
|
176
|
+
cache_hit = artifact.is_file()
|
|
177
|
+
if not cache_hit:
|
|
178
|
+
if entry.exists():
|
|
179
|
+
raise BuildError(f"incomplete cache entry at {entry}")
|
|
180
|
+
with tempfile.TemporaryDirectory(prefix=".build-", dir=root) as temp:
|
|
181
|
+
staging = Path(temp) / "crate"
|
|
182
|
+
staging.mkdir()
|
|
183
|
+
source = prelude + program.rust.replace("RUSTFY_MODULE", module)
|
|
184
|
+
start = perf_counter()
|
|
185
|
+
library = _build(staging, root / ".cargo-target", module, source)
|
|
186
|
+
build_seconds = perf_counter() - start
|
|
187
|
+
shutil.copyfile(library, staging / artifact.name)
|
|
188
|
+
staging.rename(entry)
|
|
189
|
+
|
|
190
|
+
try:
|
|
191
|
+
function = _load(module, artifact)
|
|
192
|
+
except (OSError, ImportError, AttributeError) as error:
|
|
193
|
+
raise BuildError(f"load failed: {error}") from error
|
|
194
|
+
return Native(function, artifact, cache_hit, build_seconds)
|
rustfy/_compiler.py
ADDED
|
@@ -0,0 +1,413 @@
|
|
|
1
|
+
"""Translate a small, typed Python AST to a Rust/PyO3 extension."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
from dataclasses import dataclass
|
|
5
|
+
import inspect
|
|
6
|
+
import math
|
|
7
|
+
import sys
|
|
8
|
+
import textwrap
|
|
9
|
+
from types import CodeType, FunctionType
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class Unsupported(ValueError):
|
|
13
|
+
"""A function uses Python semantics beyond the native subset."""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
INT, FLOAT, BOOL = "i64", "f64", "bool"
|
|
17
|
+
VECTORS = {"Vec<i64>": INT, "Vec<f64>": FLOAT}
|
|
18
|
+
READERS = {
|
|
19
|
+
INT: "read_int",
|
|
20
|
+
FLOAT: "read_float",
|
|
21
|
+
BOOL: "read_bool",
|
|
22
|
+
"Vec<i64>": "read_ints",
|
|
23
|
+
"Vec<f64>": "read_floats",
|
|
24
|
+
}
|
|
25
|
+
BUILTINS = dict(len=len, range=range, abs=abs, min=min, max=max, pow=pow)
|
|
26
|
+
SQRT = math.sqrt
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
@dataclass(frozen=True)
|
|
30
|
+
class Program:
|
|
31
|
+
ast_key: str
|
|
32
|
+
rust: str
|
|
33
|
+
names: frozenset[str]
|
|
34
|
+
|
|
35
|
+
def bindings_match(self, function):
|
|
36
|
+
namespace = function.__globals__
|
|
37
|
+
for name in self.names:
|
|
38
|
+
if name == "math":
|
|
39
|
+
if namespace.get("math") is not math or math.sqrt is not SQRT:
|
|
40
|
+
return False
|
|
41
|
+
elif namespace.get(name, function.__builtins__.get(name)) is not BUILTINS[name]:
|
|
42
|
+
return False
|
|
43
|
+
return True
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
@dataclass(frozen=True)
|
|
47
|
+
class Value:
|
|
48
|
+
code: str
|
|
49
|
+
kind: str
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _annotation(node):
|
|
53
|
+
if isinstance(node, ast.Constant) and isinstance(node.value, str):
|
|
54
|
+
node = ast.parse(node.value, mode="eval").body
|
|
55
|
+
if isinstance(node, ast.Name) and node.id in {"int", "float", "bool"}:
|
|
56
|
+
return {"int": INT, "float": FLOAT, "bool": BOOL}[node.id]
|
|
57
|
+
if isinstance(node, ast.Subscript) and isinstance(node.value, ast.Name) and node.value.id == "list":
|
|
58
|
+
item = _annotation(node.slice)
|
|
59
|
+
if item in (INT, FLOAT):
|
|
60
|
+
return f"Vec<{item}>"
|
|
61
|
+
raise Unsupported("annotations must be int, float, bool, list[int], or list[float]")
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _require(value, kind):
|
|
65
|
+
if value.kind != kind:
|
|
66
|
+
raise Unsupported(f"expected {kind}, found {value.kind}")
|
|
67
|
+
return value.code
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _truth(value):
|
|
71
|
+
if value.kind == BOOL:
|
|
72
|
+
return value.code
|
|
73
|
+
if value.kind == INT:
|
|
74
|
+
return f"({value.code} != 0)"
|
|
75
|
+
if value.kind == FLOAT:
|
|
76
|
+
return f"({value.code} != 0.0)"
|
|
77
|
+
raise Unsupported("expected a scalar condition")
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _float(value):
|
|
81
|
+
if value.kind == FLOAT:
|
|
82
|
+
return value.code
|
|
83
|
+
if value.kind == INT:
|
|
84
|
+
return f"({value.code} as f64)"
|
|
85
|
+
raise Unsupported("expected a number")
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
def _binary(operator, a, b):
|
|
89
|
+
kind = FLOAT if FLOAT in (a.kind, b.kind) else INT
|
|
90
|
+
if kind == FLOAT:
|
|
91
|
+
left, right = _float(a), _float(b)
|
|
92
|
+
else:
|
|
93
|
+
left, right = _require(a, INT), _require(b, INT)
|
|
94
|
+
|
|
95
|
+
if isinstance(operator, ast.Div):
|
|
96
|
+
if kind == INT:
|
|
97
|
+
return Value(f"rf::div_int({left}, {right})?", FLOAT)
|
|
98
|
+
return Value(f"rf::div_float({left}, {right})?", FLOAT)
|
|
99
|
+
|
|
100
|
+
if isinstance(operator, ast.Pow):
|
|
101
|
+
helper = "pow_float" if kind == FLOAT else "pow_int"
|
|
102
|
+
return Value(f"rf::{helper}({left}, {right})?", kind)
|
|
103
|
+
|
|
104
|
+
if isinstance(operator, (ast.FloorDiv, ast.Mod)) and kind == INT:
|
|
105
|
+
part = 0 if isinstance(operator, ast.FloorDiv) else 1
|
|
106
|
+
return Value(f"rf::divmod({left}, {right})?.{part}", INT)
|
|
107
|
+
|
|
108
|
+
arithmetic = {
|
|
109
|
+
ast.Add: ("+", "checked_add"),
|
|
110
|
+
ast.Sub: ("-", "checked_sub"),
|
|
111
|
+
ast.Mult: ("*", "checked_mul"),
|
|
112
|
+
}
|
|
113
|
+
if type(operator) not in arithmetic:
|
|
114
|
+
raise Unsupported(f"arithmetic operation {type(operator).__name__} on {kind}")
|
|
115
|
+
symbol, checked = arithmetic[type(operator)]
|
|
116
|
+
if kind == INT:
|
|
117
|
+
return Value(f"({left}).{checked}({right})?", INT)
|
|
118
|
+
return Value(f"({left} {symbol} {right})", FLOAT)
|
|
119
|
+
|
|
120
|
+
|
|
121
|
+
def _comparison(operator, a, b):
|
|
122
|
+
symbols = {
|
|
123
|
+
ast.Eq: "==", ast.NotEq: "!=", ast.Lt: "<", ast.LtE: "<=",
|
|
124
|
+
ast.Gt: ">", ast.GtE: ">=",
|
|
125
|
+
}
|
|
126
|
+
if type(operator) not in symbols:
|
|
127
|
+
raise Unsupported("unsupported comparison")
|
|
128
|
+
symbol = symbols[type(operator)]
|
|
129
|
+
if a.kind == b.kind and a.kind not in VECTORS:
|
|
130
|
+
return Value(f"({a.code} {symbol} {b.code})", BOOL)
|
|
131
|
+
if {a.kind, b.kind} == {INT, FLOAT}:
|
|
132
|
+
# A direct cast would change comparisons near the limits of f64 precision.
|
|
133
|
+
left = f"rf::exact_float({a.code})?" if a.kind == INT else a.code
|
|
134
|
+
right = f"rf::exact_float({b.code})?" if b.kind == INT else b.code
|
|
135
|
+
return Value(f"({left} {symbol} {right})", BOOL)
|
|
136
|
+
raise Unsupported("comparison of these types")
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
class Compiler:
|
|
140
|
+
def __init__(self, node, local_names):
|
|
141
|
+
self.node = node
|
|
142
|
+
self.local_names = local_names
|
|
143
|
+
self.values = {}
|
|
144
|
+
self.parameters = []
|
|
145
|
+
self.names = set()
|
|
146
|
+
self.output = _annotation(node.returns)
|
|
147
|
+
self.loop_number = 0
|
|
148
|
+
|
|
149
|
+
args = node.args
|
|
150
|
+
if args.vararg or args.kwarg:
|
|
151
|
+
raise Unsupported("variadic parameters")
|
|
152
|
+
for argument in (*args.posonlyargs, *args.args, *args.kwonlyargs):
|
|
153
|
+
self.parameters.append(self.bind(argument.arg, _annotation(argument.annotation)))
|
|
154
|
+
|
|
155
|
+
def bind(self, name, kind):
|
|
156
|
+
value = self.values.get(name)
|
|
157
|
+
if value is None:
|
|
158
|
+
value = Value(f"v{len(self.values)}", kind)
|
|
159
|
+
self.values[name] = value
|
|
160
|
+
_require(value, kind)
|
|
161
|
+
return value
|
|
162
|
+
|
|
163
|
+
def reference(self, name):
|
|
164
|
+
if name not in self.values:
|
|
165
|
+
raise Unsupported(f"unknown variable {name!r}")
|
|
166
|
+
return self.values[name]
|
|
167
|
+
|
|
168
|
+
def builtin(self, name):
|
|
169
|
+
if name in self.local_names or name not in BUILTINS:
|
|
170
|
+
raise Unsupported(f"call to {name!r}")
|
|
171
|
+
self.names.add(name)
|
|
172
|
+
|
|
173
|
+
def indexed(self, node):
|
|
174
|
+
vector = self.expression(node.value)
|
|
175
|
+
if vector.kind not in VECTORS:
|
|
176
|
+
raise Unsupported("indexing requires a vector")
|
|
177
|
+
return vector, _require(self.expression(node.slice), INT)
|
|
178
|
+
|
|
179
|
+
def expression(self, node):
|
|
180
|
+
match node:
|
|
181
|
+
case ast.Constant(value=value) if type(value) is bool:
|
|
182
|
+
return Value("true" if value else "false", BOOL)
|
|
183
|
+
case ast.Constant(value=value) if type(value) is int and -(2**63) <= value < 2**63:
|
|
184
|
+
return Value(f"{value}i64", INT)
|
|
185
|
+
case ast.Constant(value=value) if type(value) is float and math.isfinite(value):
|
|
186
|
+
return Value(f"{value!r}f64", FLOAT)
|
|
187
|
+
case ast.Name(id=name):
|
|
188
|
+
return self.reference(name)
|
|
189
|
+
case ast.Subscript():
|
|
190
|
+
vector, index = self.indexed(node)
|
|
191
|
+
return Value(f"rf::get(&{vector.code}, {index})?", VECTORS[vector.kind])
|
|
192
|
+
case ast.BinOp(left=left, op=op, right=right):
|
|
193
|
+
return _binary(op, self.expression(left), self.expression(right))
|
|
194
|
+
case ast.UnaryOp(op=ast.Not(), operand=operand):
|
|
195
|
+
return Value(f"!({_truth(self.expression(operand))})", BOOL)
|
|
196
|
+
case ast.UnaryOp(op=ast.USub(), operand=ast.Constant(value=9223372036854775808)):
|
|
197
|
+
if type(node.operand.value) is int:
|
|
198
|
+
return Value("i64::MIN", INT)
|
|
199
|
+
return self.negate(self.expression(node.operand))
|
|
200
|
+
case ast.UnaryOp(op=ast.USub(), operand=operand):
|
|
201
|
+
return self.negate(self.expression(operand))
|
|
202
|
+
case ast.UnaryOp(op=ast.UAdd(), operand=operand):
|
|
203
|
+
value = self.expression(operand)
|
|
204
|
+
if value.kind in (INT, FLOAT):
|
|
205
|
+
return value
|
|
206
|
+
case ast.Compare(left=left, ops=[op], comparators=[right]):
|
|
207
|
+
return _comparison(op, self.expression(left), self.expression(right))
|
|
208
|
+
case ast.BoolOp(op=op, values=values):
|
|
209
|
+
operator = " && " if isinstance(op, ast.And) else " || "
|
|
210
|
+
parts = [_require(self.expression(part), BOOL) for part in values]
|
|
211
|
+
return Value(f"({operator.join(parts)})", BOOL)
|
|
212
|
+
case ast.IfExp(test=test, body=body, orelse=otherwise):
|
|
213
|
+
left, right = self.expression(body), self.expression(otherwise)
|
|
214
|
+
if left.kind in VECTORS:
|
|
215
|
+
raise Unsupported("vector expressions require a local variable")
|
|
216
|
+
condition = _truth(self.expression(test))
|
|
217
|
+
return Value(f"(if {condition} {{ {left.code} }} else {{ {_require(right, left.kind)} }})", left.kind)
|
|
218
|
+
case ast.Call(func=func, args=args, keywords=[]):
|
|
219
|
+
return self.call(func, [self.expression(arg) for arg in args])
|
|
220
|
+
kind = type(node).__name__
|
|
221
|
+
raise Unsupported(f"expression {kind} on line {getattr(node, 'lineno', '?')}")
|
|
222
|
+
|
|
223
|
+
@staticmethod
|
|
224
|
+
def negate(value):
|
|
225
|
+
if value.kind == FLOAT:
|
|
226
|
+
return Value(f"(-({value.code}))", FLOAT)
|
|
227
|
+
return Value(f"({_require(value, INT)}).checked_neg()?", INT)
|
|
228
|
+
|
|
229
|
+
def call(self, func, args):
|
|
230
|
+
match func:
|
|
231
|
+
case ast.Attribute(value=ast.Name(id="math"), attr="sqrt") if len(args) == 1:
|
|
232
|
+
if "math" in self.local_names:
|
|
233
|
+
raise Unsupported("math is shadowed by a local variable")
|
|
234
|
+
self.names.add("math")
|
|
235
|
+
return Value(f"rf::sqrt({_float(args[0])})?", FLOAT)
|
|
236
|
+
case ast.Name(id=name):
|
|
237
|
+
self.builtin(name)
|
|
238
|
+
if name == "len" and len(args) == 1 and args[0].kind in VECTORS:
|
|
239
|
+
return Value(f"({args[0].code}.len() as i64)", INT)
|
|
240
|
+
if name == "abs" and len(args) == 1:
|
|
241
|
+
arg = args[0]
|
|
242
|
+
if arg.kind == FLOAT:
|
|
243
|
+
return Value(f"({arg.code}).abs()", FLOAT)
|
|
244
|
+
return Value(f"({_require(arg, INT)}).checked_abs()?", INT)
|
|
245
|
+
if name in ("min", "max") and len(args) >= 2 and args[0].kind not in VECTORS:
|
|
246
|
+
kind = args[0].kind
|
|
247
|
+
code = args[0].code
|
|
248
|
+
for arg in args[1:]:
|
|
249
|
+
code = f"rf::{name}({code}, {_require(arg, kind)})"
|
|
250
|
+
return Value(code, kind)
|
|
251
|
+
if name == "pow" and len(args) == 2:
|
|
252
|
+
return _binary(ast.Pow(), *args)
|
|
253
|
+
raise Unsupported("unsupported call")
|
|
254
|
+
|
|
255
|
+
def assign(self, target, value):
|
|
256
|
+
match target:
|
|
257
|
+
case ast.Name(id=name):
|
|
258
|
+
if value.kind in VECTORS:
|
|
259
|
+
raise Unsupported("use an annotated empty list for local vectors")
|
|
260
|
+
variable = self.bind(name, value.kind)
|
|
261
|
+
return f"{variable.code} = {value.code};"
|
|
262
|
+
case ast.Subscript():
|
|
263
|
+
vector, index = self.indexed(target)
|
|
264
|
+
self.mutable_vector(vector)
|
|
265
|
+
rhs = _require(value, VECTORS[vector.kind])
|
|
266
|
+
return f"{{ let rhs = {rhs}; let index = {index}; *rf::at_mut(&mut {vector.code}, index)? = rhs; }}"
|
|
267
|
+
raise Unsupported("unsupported assignment target")
|
|
268
|
+
|
|
269
|
+
def mutable_vector(self, value):
|
|
270
|
+
if value.kind not in VECTORS or value in self.parameters:
|
|
271
|
+
raise Unsupported("only locally allocated vectors can be mutated")
|
|
272
|
+
|
|
273
|
+
def for_loop(self, target, args, body, depth):
|
|
274
|
+
self.builtin("range")
|
|
275
|
+
values = [_require(self.expression(arg), INT) for arg in args]
|
|
276
|
+
if len(values) == 1:
|
|
277
|
+
values.insert(0, "0i64")
|
|
278
|
+
iterator = (
|
|
279
|
+
f"({values[0]})..({values[1]})" if len(values) == 2
|
|
280
|
+
else f"rf::Range::new({', '.join(values)})?"
|
|
281
|
+
)
|
|
282
|
+
variable = self.bind(target, INT).code
|
|
283
|
+
index = f"index{self.loop_number}"
|
|
284
|
+
self.loop_number += 1
|
|
285
|
+
return (
|
|
286
|
+
f"for {index} in {iterator} {{\n"
|
|
287
|
+
f"{' ' * (depth + 1)}{variable} = {index};\n{self.block(body, depth + 1)}\n"
|
|
288
|
+
f"{' ' * depth}}}"
|
|
289
|
+
)
|
|
290
|
+
|
|
291
|
+
def statement(self, node, depth):
|
|
292
|
+
indent = " " * depth
|
|
293
|
+
match node:
|
|
294
|
+
case ast.Return(value=expr) if expr is not None:
|
|
295
|
+
value = self.expression(expr)
|
|
296
|
+
if value in self.parameters and value.kind in VECTORS:
|
|
297
|
+
raise Unsupported("return a new list")
|
|
298
|
+
return f"return Some({_require(value, self.output)});"
|
|
299
|
+
case ast.Assign(targets=[target], value=expr):
|
|
300
|
+
return self.assign(target, self.expression(expr))
|
|
301
|
+
case ast.AnnAssign(target=ast.Name(id=name), annotation=annotation, value=expr) if expr is not None:
|
|
302
|
+
kind = _annotation(annotation)
|
|
303
|
+
if kind in VECTORS and isinstance(expr, ast.List) and not expr.elts:
|
|
304
|
+
variable = self.bind(name, kind)
|
|
305
|
+
self.mutable_vector(variable)
|
|
306
|
+
return f"{variable.code} = Vec::new();"
|
|
307
|
+
value = self.expression(expr)
|
|
308
|
+
_require(value, kind)
|
|
309
|
+
return self.assign(node.target, value)
|
|
310
|
+
case ast.AugAssign(target=ast.Name(id=name), op=op, value=expr):
|
|
311
|
+
result = _binary(op, self.reference(name), self.expression(expr))
|
|
312
|
+
return self.assign(node.target, result)
|
|
313
|
+
case ast.Expr(value=ast.Call(
|
|
314
|
+
func=ast.Attribute(value=ast.Name(id=name), attr="append"), args=[expr], keywords=[]
|
|
315
|
+
)):
|
|
316
|
+
vector = self.reference(name)
|
|
317
|
+
self.mutable_vector(vector)
|
|
318
|
+
return f"{vector.code}.push({_require(self.expression(expr), VECTORS[vector.kind])});"
|
|
319
|
+
case ast.For(
|
|
320
|
+
target=ast.Name(id=target),
|
|
321
|
+
iter=ast.Call(func=ast.Name(id="range"), args=args, keywords=[]), body=body, orelse=[]
|
|
322
|
+
) if 1 <= len(args) <= 3:
|
|
323
|
+
return self.for_loop(target, args, body, depth)
|
|
324
|
+
case ast.While(test=test, body=body, orelse=[]):
|
|
325
|
+
condition = _truth(self.expression(test))
|
|
326
|
+
return f"while {condition} {{\n{self.block(body, depth + 1)}\n{indent}}}"
|
|
327
|
+
case ast.If(test=test, body=body, orelse=otherwise):
|
|
328
|
+
condition = _truth(self.expression(test))
|
|
329
|
+
code = f"if {condition} {{\n{self.block(body, depth + 1)}\n{indent}}}"
|
|
330
|
+
if otherwise:
|
|
331
|
+
code += f" else {{\n{self.block(otherwise, depth + 1)}\n{indent}}}"
|
|
332
|
+
return code
|
|
333
|
+
case ast.Pass():
|
|
334
|
+
return ""
|
|
335
|
+
case ast.Break():
|
|
336
|
+
return "break;"
|
|
337
|
+
case ast.Continue():
|
|
338
|
+
return "continue;"
|
|
339
|
+
raise Unsupported(f"statement {type(node).__name__} on line {node.lineno}")
|
|
340
|
+
|
|
341
|
+
def block(self, nodes, depth):
|
|
342
|
+
indent = " " * depth
|
|
343
|
+
return "\n".join(indent + self.statement(node, depth) for node in nodes)
|
|
344
|
+
|
|
345
|
+
def compile(self):
|
|
346
|
+
body = self.node.body
|
|
347
|
+
if ast.get_docstring(self.node, clean=False) is not None:
|
|
348
|
+
body = body[1:]
|
|
349
|
+
statements = self.block(body, 1)
|
|
350
|
+
bindings = [f"{value.code}: {value.kind}" for value in self.parameters]
|
|
351
|
+
arguments = ", ".join("mut " + binding for binding in bindings)
|
|
352
|
+
declarations = "\n".join(
|
|
353
|
+
f" let mut {value.code}: {value.kind};"
|
|
354
|
+
for value in self.values.values()
|
|
355
|
+
if value not in self.parameters
|
|
356
|
+
)
|
|
357
|
+
py_args = ", ".join(f"p{i}: &Bound<'_, PyAny>" for i, _ in enumerate(self.parameters))
|
|
358
|
+
conversions = ", ".join(
|
|
359
|
+
f"rf::{READERS[value.kind]}(p{i})?" for i, value in enumerate(self.parameters)
|
|
360
|
+
)
|
|
361
|
+
return f"""
|
|
362
|
+
fn kernel({arguments}) -> Option<{self.output}> {{
|
|
363
|
+
{declarations}
|
|
364
|
+
{statements}
|
|
365
|
+
None
|
|
366
|
+
}}
|
|
367
|
+
|
|
368
|
+
#[pyfunction]
|
|
369
|
+
fn run({py_args}) -> PyResult<{self.output}> {{
|
|
370
|
+
kernel({conversions}).ok_or_else(|| PyValueError::new_err("operation outside the native contract"))
|
|
371
|
+
}}
|
|
372
|
+
|
|
373
|
+
#[pymodule]
|
|
374
|
+
fn RUSTFY_MODULE(module: &Bound<'_, PyModule>) -> PyResult<()> {{
|
|
375
|
+
module.add_function(wrap_pyfunction!(run, module)?)
|
|
376
|
+
}}
|
|
377
|
+
"""
|
|
378
|
+
|
|
379
|
+
|
|
380
|
+
def _find_code(module_code, active):
|
|
381
|
+
for value in module_code.co_consts:
|
|
382
|
+
if not isinstance(value, CodeType):
|
|
383
|
+
continue
|
|
384
|
+
if value.co_name == active.co_name and value.co_firstlineno == active.co_firstlineno:
|
|
385
|
+
return value
|
|
386
|
+
nested = _find_code(value, active)
|
|
387
|
+
if nested is not None:
|
|
388
|
+
return nested
|
|
389
|
+
return None
|
|
390
|
+
|
|
391
|
+
|
|
392
|
+
def compile_function(function):
|
|
393
|
+
if not isinstance(function, FunctionType) or function.__closure__:
|
|
394
|
+
raise Unsupported("expected a function without captured variables")
|
|
395
|
+
live_code = function.__code__
|
|
396
|
+
lines, first = inspect.findsource(function)
|
|
397
|
+
source = textwrap.dedent("".join(inspect.getblock(lines[first:])))
|
|
398
|
+
tree = ast.parse(source)
|
|
399
|
+
if len(tree.body) != 1 or not isinstance(tree.body[0], ast.FunctionDef):
|
|
400
|
+
raise Unsupported("expected a synchronous function definition")
|
|
401
|
+
node = tree.body[0]
|
|
402
|
+
node.decorator_list = []
|
|
403
|
+
|
|
404
|
+
# Compile the whole source without executing it. Module imports can affect
|
|
405
|
+
# CPython bytecode generation, and the on-disk function may have been edited.
|
|
406
|
+
module = compile("".join(lines), live_code.co_filename, "exec",
|
|
407
|
+
dont_inherit=True, optimize=sys.flags.optimize)
|
|
408
|
+
if _find_code(module, live_code) != live_code:
|
|
409
|
+
raise Unsupported("source differs from the active Python function")
|
|
410
|
+
|
|
411
|
+
compiler = Compiler(node, set(live_code.co_varnames))
|
|
412
|
+
rust = compiler.compile()
|
|
413
|
+
return Program(ast.dump(tree, include_attributes=False), rust, frozenset(compiler.names))
|
rustfy/_prelude.rs
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
#![allow(dead_code, unreachable_code, unused_assignments, unused_mut, unused_parens, unused_variables)]
|
|
2
|
+
|
|
3
|
+
use pyo3::exceptions::PyValueError;
|
|
4
|
+
use pyo3::prelude::*;
|
|
5
|
+
|
|
6
|
+
mod rf {
|
|
7
|
+
use pyo3::prelude::*;
|
|
8
|
+
use pyo3::types::{PyBool, PyFloat, PyInt, PyList};
|
|
9
|
+
|
|
10
|
+
pub fn read_int(value: &Bound<'_, PyAny>) -> PyResult<i64> {
|
|
11
|
+
value.cast_exact::<PyInt>()?.extract()
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
pub fn read_float(value: &Bound<'_, PyAny>) -> PyResult<f64> {
|
|
15
|
+
Ok(value.cast_exact::<PyFloat>()?.value())
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
pub fn read_bool(value: &Bound<'_, PyAny>) -> PyResult<bool> {
|
|
19
|
+
Ok(value.cast_exact::<PyBool>()?.is_true())
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
pub fn read_ints(value: &Bound<'_, PyAny>) -> PyResult<Vec<i64>> {
|
|
23
|
+
let list = value.cast_exact::<PyList>()?;
|
|
24
|
+
let mut values = Vec::with_capacity(list.len());
|
|
25
|
+
for item in list.iter() {
|
|
26
|
+
values.push(read_int(&item)?);
|
|
27
|
+
}
|
|
28
|
+
Ok(values)
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
pub fn read_floats(value: &Bound<'_, PyAny>) -> PyResult<Vec<f64>> {
|
|
32
|
+
let list = value.cast_exact::<PyList>()?;
|
|
33
|
+
let mut values = Vec::with_capacity(list.len());
|
|
34
|
+
for item in list.iter() {
|
|
35
|
+
values.push(read_float(&item)?);
|
|
36
|
+
}
|
|
37
|
+
Ok(values)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
#[inline]
|
|
41
|
+
fn index_of(len: usize, index: i64) -> Option<usize> {
|
|
42
|
+
let index = if index < 0 { index + len as i64 } else { index };
|
|
43
|
+
usize::try_from(index).ok()
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
#[inline]
|
|
47
|
+
pub fn get<T: Copy>(values: &[T], index: i64) -> Option<T> {
|
|
48
|
+
values.get(index_of(values.len(), index)?).copied()
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
#[inline]
|
|
52
|
+
pub fn at_mut<T>(values: &mut [T], index: i64) -> Option<&mut T> {
|
|
53
|
+
values.get_mut(index_of(values.len(), index)?)
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
#[inline]
|
|
57
|
+
pub fn exact_float(value: i64) -> Option<f64> {
|
|
58
|
+
const LIMIT: i64 = 1 << 53;
|
|
59
|
+
(-LIMIT..=LIMIT).contains(&value).then_some(value as f64)
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
#[inline]
|
|
63
|
+
pub fn div_int(left: i64, right: i64) -> Option<f64> {
|
|
64
|
+
div_float(exact_float(left)?, exact_float(right)?)
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
#[inline]
|
|
68
|
+
pub fn div_float(left: f64, right: f64) -> Option<f64> {
|
|
69
|
+
(right != 0.0).then(|| left / right)
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
#[inline]
|
|
73
|
+
pub fn divmod(left: i64, right: i64) -> Option<(i64, i64)> {
|
|
74
|
+
let quotient = left.checked_div(right)?;
|
|
75
|
+
let remainder = left % right;
|
|
76
|
+
if remainder != 0 && (remainder < 0) != (right < 0) {
|
|
77
|
+
Some((quotient - 1, remainder + right))
|
|
78
|
+
} else {
|
|
79
|
+
Some((quotient, remainder))
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
#[inline]
|
|
84
|
+
pub fn pow_int(left: i64, right: i64) -> Option<i64> {
|
|
85
|
+
left.checked_pow(u32::try_from(right).ok()?)
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
#[inline]
|
|
89
|
+
pub fn pow_float(left: f64, right: f64) -> Option<f64> {
|
|
90
|
+
if !left.is_finite() || !right.is_finite() || (left == 0.0 && right < 0.0) {
|
|
91
|
+
return None;
|
|
92
|
+
}
|
|
93
|
+
let value = left.powf(right);
|
|
94
|
+
value.is_finite().then_some(value)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
#[inline]
|
|
98
|
+
pub fn sqrt(value: f64) -> Option<f64> {
|
|
99
|
+
(value >= 0.0 || value.is_nan()).then(|| value.sqrt())
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
#[inline]
|
|
103
|
+
pub fn min<T: PartialOrd>(left: T, right: T) -> T {
|
|
104
|
+
if right < left { right } else { left }
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
#[inline]
|
|
108
|
+
pub fn max<T: PartialOrd>(left: T, right: T) -> T {
|
|
109
|
+
if right > left { right } else { left }
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
pub struct Range {
|
|
113
|
+
next: Option<i64>,
|
|
114
|
+
stop: i64,
|
|
115
|
+
step: i64,
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
impl Range {
|
|
119
|
+
pub fn new(start: i64, stop: i64, step: i64) -> Option<Self> {
|
|
120
|
+
(step != 0).then_some(Self { next: Some(start), stop, step })
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
impl Iterator for Range {
|
|
125
|
+
type Item = i64;
|
|
126
|
+
|
|
127
|
+
fn next(&mut self) -> Option<i64> {
|
|
128
|
+
let value = self.next?;
|
|
129
|
+
if (self.step > 0 && value >= self.stop) || (self.step < 0 && value <= self.stop) {
|
|
130
|
+
self.next = None;
|
|
131
|
+
return None;
|
|
132
|
+
}
|
|
133
|
+
self.next = value.checked_add(self.step);
|
|
134
|
+
Some(value)
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
}
|
rustfy/cli.py
ADDED
|
@@ -0,0 +1,111 @@
|
|
|
1
|
+
"""Run the Python and native versions of a benchmark on identical inputs."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
from pathlib import Path
|
|
5
|
+
import runpy
|
|
6
|
+
from statistics import median
|
|
7
|
+
import sys
|
|
8
|
+
from time import perf_counter_ns
|
|
9
|
+
|
|
10
|
+
from . import _CHECKS, _Runner
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _elapsed(function, args):
|
|
14
|
+
start = perf_counter_ns()
|
|
15
|
+
function(*args)
|
|
16
|
+
return perf_counter_ns() - start
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _measure(python, native, args, repeats):
|
|
20
|
+
calls = (python, native)
|
|
21
|
+
times = ([], [])
|
|
22
|
+
for repeat in range(repeats):
|
|
23
|
+
for index in ((0, 1) if repeat % 2 == 0 else (1, 0)):
|
|
24
|
+
times[index].append(_elapsed(calls[index], args))
|
|
25
|
+
return tuple(median(group) / 1_000_000 for group in times)
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
def _benchmark(path, repeats):
|
|
29
|
+
sys.path.insert(0, str(path.parent))
|
|
30
|
+
try:
|
|
31
|
+
namespace = runpy.run_path(str(path), run_name="__rustfy_bench__")
|
|
32
|
+
runner = getattr(namespace.get("BENCHMARK"), "_rustfy_runner", None)
|
|
33
|
+
cases = namespace.get("benchmark_cases")
|
|
34
|
+
if not isinstance(runner, _Runner) or not callable(cases):
|
|
35
|
+
raise ValueError("define a decorated BENCHMARK and a benchmark_cases() function")
|
|
36
|
+
_report(path, runner, cases(), repeats)
|
|
37
|
+
finally:
|
|
38
|
+
sys.path.pop(0)
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _report(path, runner, cases, repeats):
|
|
42
|
+
runner.prepare()
|
|
43
|
+
info = runner.info()
|
|
44
|
+
if info.backend != "rust":
|
|
45
|
+
raise RuntimeError(info.reason or "native backend unavailable")
|
|
46
|
+
|
|
47
|
+
print(f"rustfy bench | {path.name} | {repeats} timed calls per backend")
|
|
48
|
+
build = "cache hit" if info.cache_hit else "fresh extension"
|
|
49
|
+
print(f"Build: {info.build_seconds:.3f} s ({build})")
|
|
50
|
+
print()
|
|
51
|
+
print(f"{'Size':>12} | {'Python ms':>10} | {'Rust ms':>10} | {'Speedup':>8} | {'Check ms':>10} | Verification")
|
|
52
|
+
print("-" * 88)
|
|
53
|
+
checkmark = "✓"
|
|
54
|
+
try:
|
|
55
|
+
checkmark.encode(sys.stdout.encoding or "utf-8")
|
|
56
|
+
except UnicodeEncodeError:
|
|
57
|
+
checkmark = "OK"
|
|
58
|
+
faster_sizes = []
|
|
59
|
+
seen = set()
|
|
60
|
+
|
|
61
|
+
def native(*args):
|
|
62
|
+
return runner.call_native(args, {})
|
|
63
|
+
|
|
64
|
+
for size, args in cases:
|
|
65
|
+
if type(size) is not int or size < 1 or size in seen or not isinstance(args, tuple):
|
|
66
|
+
raise ValueError("each case must be a unique positive integer size and an argument tuple")
|
|
67
|
+
seen.add(size)
|
|
68
|
+
|
|
69
|
+
start = perf_counter_ns()
|
|
70
|
+
for check in range(1, _CHECKS + 1):
|
|
71
|
+
if not runner.compare(runner.function(*args), native(*args)):
|
|
72
|
+
print(f"{size:>12,} | verification failed after {check - 1}/{_CHECKS} matches")
|
|
73
|
+
raise RuntimeError(runner.info().reason)
|
|
74
|
+
verification_ms = (perf_counter_ns() - start) / 1_000_000
|
|
75
|
+
|
|
76
|
+
python_ms, rust_ms = _measure(runner.function, native, args, repeats)
|
|
77
|
+
speedup = python_ms / rust_ms
|
|
78
|
+
if speedup > 1:
|
|
79
|
+
faster_sizes.append(size)
|
|
80
|
+
print(
|
|
81
|
+
f"{size:>12,} | {python_ms:>10.3f} | {rust_ms:>10.3f} | {speedup:>7.2f}x"
|
|
82
|
+
f" | {verification_ms:>10.3f} | {checkmark} 100% match ({_CHECKS}/{_CHECKS})"
|
|
83
|
+
)
|
|
84
|
+
|
|
85
|
+
if not seen:
|
|
86
|
+
raise ValueError("benchmark_cases() did not yield any cases")
|
|
87
|
+
crossover = f"{min(faster_sizes):,} (smallest tested size with a faster native call)" if faster_sizes else "not observed"
|
|
88
|
+
print(f"\nCrossover: {crossover}")
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _positive(value):
|
|
92
|
+
integer = int(value)
|
|
93
|
+
if integer < 1:
|
|
94
|
+
raise argparse.ArgumentTypeError("expected a positive integer")
|
|
95
|
+
return integer
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
def main(argv=None):
|
|
99
|
+
parser = argparse.ArgumentParser(prog="rustfy")
|
|
100
|
+
subcommands = parser.add_subparsers(dest="command", required=True)
|
|
101
|
+
bench = subcommands.add_parser("bench", help="compare a script's Python and Rust implementations")
|
|
102
|
+
bench.add_argument("script", type=Path)
|
|
103
|
+
bench.add_argument("--repeats", type=_positive, default=5)
|
|
104
|
+
options = parser.parse_args(argv)
|
|
105
|
+
|
|
106
|
+
try:
|
|
107
|
+
_benchmark(options.script.resolve(strict=True), options.repeats)
|
|
108
|
+
except Exception as error:
|
|
109
|
+
print(f"rustfy bench: {error}", file=sys.stderr)
|
|
110
|
+
return 1
|
|
111
|
+
return 0
|
|
@@ -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)
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
rustfy/__init__.py,sha256=69fN5NFIf8JKjt8w64Aa6FjO0I7ToOklD9WyEm0-pA4,6316
|
|
2
|
+
rustfy/__main__.py,sha256=SCuGk-L-bb1zLj15YeA4J9PvoYe60R0p2hiL5YDrvuo,51
|
|
3
|
+
rustfy/_build.py,sha256=VXKApY14g9sPGNTkkzQRf3oLO4PF2tmKy7r0Ab_mcQ8,6344
|
|
4
|
+
rustfy/_compiler.py,sha256=EawVrtUUirUWsdWlTDaxrShhnSw3_oNcf4wYrFpEqc8,17678
|
|
5
|
+
rustfy/_prelude.rs,sha256=Tnm0OM3kkF1OEt5FNCQpQfURlHqtS5yOo75BUSxZLBA,4098
|
|
6
|
+
rustfy/cli.py,sha256=_e8uIL7KLNmnS5gHRFO61OPan4bDXhsLUnjXEWeTeRU,4119
|
|
7
|
+
rustfy-0.1.0.dist-info/licenses/LICENSE,sha256=xJy70wHonrFlX7VxrseHC2OFsCm6f9eYGTRjJ7U9tQY,1091
|
|
8
|
+
rustfy-0.1.0.dist-info/METADATA,sha256=6vh33kPQxGZfFMkXvkSwdl6HqFL7TZRZmFQB9sWh3Ss,6802
|
|
9
|
+
rustfy-0.1.0.dist-info/WHEEL,sha256=mOdXR9C3wMVov7cSY8PY-XCzo3SmmWCHvGQr5csJoao,91
|
|
10
|
+
rustfy-0.1.0.dist-info/entry_points.txt,sha256=QcOdi49wie2BMqL5FrMDLR6Em_0GD4M0RBHAKej2VWo,43
|
|
11
|
+
rustfy-0.1.0.dist-info/top_level.txt,sha256=gr1qMJqueFXXegnpLl_RSlRTcmmLzouJnmpyRwE5i-4,7
|
|
12
|
+
rustfy-0.1.0.dist-info/RECORD,,
|
|
@@ -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.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
rustfy
|