Skip to content

Don't rewrite it in Rust. Rewrite the 5% that's slow: profile your app, port the hot functions with your coding agent, prove they behave the same. Python, JS/TS, Ruby, Java, Kotlin, Go, PHP, C/C++, C#, R.

python: port functions that take or return dataclasses and NamedTuples (#47)

chessMan171c52457441
diff --git a/README.md b/README.md
index 5efa656..02339b2 100644
--- a/README.md
+++ b/README.md
@@ -101,7 +101,7 @@ fast-anything ports the outermost loop it can, not the tiny function called insi
| C and C++ (gcc, clang or Intel oneAPI icx/icpx: `clang -O2 main.c lib.c`) | the same C bridge, through LoadLibrary or dlopen | ✅ |
| C# / .NET 8+ (`dotnet run -c Release`) | the same C bridge, through NativeLibrary; profiled with EventPipe, nothing to install | ✅ |
-It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s, in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
+It ports top-level, deterministic functions that take plain data (numbers, strings, lists, dicts, typed arrays…), including ones in your entry script when its main code sits under `if __name__ == "__main__":` (or `if __FILE__ == $0`, or `if (import.meta.main)` / `if (require.main === module)`). In Python that means module-level functions and `@staticmethod`s (dataclasses and NamedTuples count as plain data), in Java, C# and PHP static methods (and PHP functions), in Go plain functions, in C and C++ free functions and static methods. `scan` says why anything else can't move yet.
With Intel oneAPI on Windows, run fast-anything from a shell where `setvars.bat` ran (it sets up the linker). SYCL kernels run on the device and aren't ported; with `-fsycl`, only host functions are profiled and ported.
diff --git a/src/hotspot.rs b/src/hotspot.rs
index 438c333..d23bb81 100644
--- a/src/hotspot.rs
+++ b/src/hotspot.rs
@@ -48,6 +48,8 @@ pub struct Hotspot {
/// Ruby: the module (or Object) whose method this is, as a Ruby expression.
/// Python: the class of a @staticmethod.
pub owner: Option<String>,
+ /// Python: dataclasses and NamedTuples from the same file that the signature uses, with their fields.
+ pub records: std::collections::BTreeMap<String, Vec<Param>>,
}
impl Hotspot {
diff --git a/src/python.rs b/src/python.rs
index fd53bb8..5d9949c 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -158,6 +158,11 @@ pub fn record(
/// Rust type for a Python annotation, if there's an obvious one.
pub fn rust_type(annotation: &str, owned: bool) -> Option<String> {
+ rust_type_in(annotation, owned, &|_| None)
+}
+
+/// rust_type, with `known` naming the Rust type for other names (structs generated for dataclasses).
+fn rust_type_in(annotation: &str, owned: bool, known: &dyn Fn(&str) -> Option<String>) -> Option<String> {
let a: String = annotation.chars().filter(|c| !c.is_whitespace()).collect();
let a = a.trim_start_matches("typing.");
let inner = |prefix: &[&str]| {
@@ -166,7 +171,7 @@ pub fn rust_type(annotation: &str, owned: bool) -> Option<String> {
.find_map(|p| a.strip_prefix(p).and_then(|r| r.strip_prefix('[')).and_then(|r| r.strip_suffix(']')))
};
if let Some(x) = a.strip_suffix("|None").or_else(|| a.strip_prefix("None|")).or_else(|| inner(&["Optional"])) {
- return rust_type(x, owned).map(|t| format!("Option<{t}>"));
+ return rust_type_in(x, owned, known).map(|t| format!("Option<{t}>"));
}
Some(match a {
"int" => "i64".into(),
@@ -180,14 +185,16 @@ pub fn rust_type(annotation: &str, owned: bool) -> Option<String> {
"bytearray" => "&[u8]".into(),
"None" if owned => "()".into(),
_ => {
- if let Some(x) = inner(&["list", "List", "Sequence"]) {
- format!("Vec<{}>", rust_type(x, true)?)
+ if let Some(t) = known(a) {
+ t
+ } else if let Some(x) = inner(&["list", "List", "Sequence"]) {
+ format!("Vec<{}>", rust_type_in(x, true, known)?)
} else if let Some(x) = inner(&["tuple", "Tuple"]) {
let raw_parts = split_top(x);
if raw_parts.len() == 2 && raw_parts[1].trim() == "..." {
- format!("Vec<{}>", rust_type(&raw_parts[0], true)?)
+ format!("Vec<{}>", rust_type_in(&raw_parts[0], true, known)?)
} else {
- let parts: Option<Vec<String>> = raw_parts.iter().map(|p| rust_type(p, true)).collect();
+ let parts: Option<Vec<String>> = raw_parts.iter().map(|p| rust_type_in(p, true, known)).collect();
let parts = parts?;
if parts.iter().any(|p| p == "...") {
return None;
@@ -199,10 +206,14 @@ pub fn rust_type(annotation: &str, owned: bool) -> Option<String> {
if kv.len() != 2 {
return None;
}
- format!("std::collections::HashMap<{}, {}>", rust_type(&kv[0], true)?, rust_type(&kv[1], true)?)
+ format!(
+ "std::collections::HashMap<{}, {}>",
+ rust_type_in(&kv[0], true, known)?,
+ rust_type_in(&kv[1], true, known)?
+ )
} else {
let x = inner(&["set", "Set", "frozenset"])?;
- format!("std::collections::HashSet<{}>", rust_type(x, true)?)
+ format!("std::collections::HashSet<{}>", rust_type_in(x, true, known)?)
}
}
})
@@ -259,13 +270,90 @@ fn signature_default(p: &crate::hotspot::Param) -> Option<String> {
p.default.as_deref().map(|d| rust_default(d).unwrap_or_else(|| "None".into()))
}
+/// The annotation names this class (as a whole word: Point in list[Point], not in PointCloud).
+fn mentions(annotation: Option<&str>, class: &str) -> bool {
+ annotation.is_some_and(|a| a.split(|c: char| !c.is_alphanumeric() && c != '_').any(|w| w == class))
+}
+
+/// Rust name for the struct of a dataclass or NamedTuple: its own, unless that would hide a Rust
+/// prelude type (a NamedTuple called Box).
+fn struct_name(class: &str) -> String {
+ const PRELUDE: &[&str] = &[
+ "Box",
+ "Vec",
+ "String",
+ "Option",
+ "Some",
+ "None",
+ "Result",
+ "Ok",
+ "Err",
+ "Self",
+ "Copy",
+ "Clone",
+ "Send",
+ "Sync",
+ "Sized",
+ "Drop",
+ "Fn",
+ "FnMut",
+ "FnOnce",
+ "Default",
+ "Iterator",
+ "ToString",
+ "ToOwned",
+ "Into",
+ "From",
+ "AsRef",
+ "AsMut",
+ "Eq",
+ "PartialEq",
+ "Ord",
+ "PartialOrd",
+ "Extend",
+ "IntoIterator",
+ "Unpin",
+ ];
+ if PRELUDE.contains(&class) { format!("Py{class}") } else { class.to_string() }
+}
+
+/// `#[derive(FromPyObject)]` structs for the dataclasses and NamedTuples the parameters use, when
+/// every field has a Rust type; PyO3 reads them field by field, by attribute.
+/// Returns (Python class name, Rust struct definition).
+fn record_structs(hs: &Hotspot) -> Vec<(String, String)> {
+ let mut out = vec![];
+ let in_params = |name: &str| hs.params.iter().any(|p| mentions(p.annotation.as_deref(), name));
+ for (name, fields) in hs.records.iter().filter(|(name, _)| in_params(name)) {
+ let Some(types) =
+ fields.iter().map(|f| f.annotation.as_deref().and_then(|a| rust_type(a, true))).collect::<Option<Vec<_>>>()
+ else {
+ continue;
+ };
+ let mut def = format!("#[derive(FromPyObject)]\n#[allow(dead_code)]\nstruct {} {{\n", struct_name(name));
+ for (f, ty) in fields.iter().zip(types) {
+ if ident(&f.name) != f.name {
+ def.push_str(&format!(" #[pyo3(attribute(\"{}\"))]\n", f.name));
+ }
+ def.push_str(&format!(" {}: {ty},\n", ident(&f.name)));
+ }
+ def.push_str("}\n\n");
+ out.push((name.clone(), def));
+ }
+ out
+}
+
pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {
+ let structs = record_structs(hs);
+ let known = |a: &str| structs.iter().any(|(name, _)| name == a).then(|| struct_name(a));
let params: Vec<String> = hs
.params
.iter()
.map(|p| {
- let ty =
- p.annotation.as_deref().and_then(|a| rust_type(a, false)).unwrap_or_else(|| "&Bound<'_, PyAny>".into());
+ let ty = p
+ .annotation
+ .as_deref()
+ .and_then(|a| rust_type_in(a, false, &known))
+ .unwrap_or_else(|| "&Bound<'_, PyAny>".into());
let ty = if signature_default(p).as_deref() == Some("None") && !ty.starts_with("Option<") {
format!("Option<{ty}>")
} else {
@@ -295,6 +383,7 @@ pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {
//! Replace the todo!() with a faithful, fast port. TASK.md has the original and real calls.\n\
//! Check it with: fast-anything verify {id}\n\n\
use pyo3::prelude::*;\n\n\
+ {structs}\
#[pyfunction]\n\
{signature}\
#[allow(unused_variables)]\n\
@@ -307,6 +396,7 @@ pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {
func = ident(&hs.name),
params = params.join(", "),
ext = port.ext,
+ structs = structs.iter().map(|(_, def)| def.as_str()).collect::<String>(),
)
}
@@ -359,6 +449,17 @@ fn py_value(v: &Value) -> String {
format!("__import__('base64').b64decode({s:?})")
}
Some((tag, Value::String(s))) if tag == "$float" => format!("float({s:?})"),
+ Some((tag, Value::Array(parts))) if tag == "$obj" && parts.len() == 3 => {
+ let class = parts[1].as_str().unwrap_or_default();
+ let fields: Vec<String> = parts[2]
+ .as_array()
+ .into_iter()
+ .flatten()
+ .filter_map(|f| f.as_array().filter(|f| f.len() == 2))
+ .map(|f| format!("{}={}", f[0].as_str().unwrap_or_default(), py_value(&f[1])))
+ .collect();
+ format!("{}({})", class.rsplit('.').next().unwrap_or(class), fields.join(", "))
+ }
_ => v.to_string(),
},
}
@@ -395,6 +496,25 @@ pub fn task_md(hs: &Hotspot, helpers: &[Hotspot], port: &Port, crate_dir: &Path)
for w in &hs.warnings {
notes.push_str(&format!("- Note: {w}.\n"));
}
+ let structs: Vec<String> = record_structs(hs).into_iter().map(|(name, _)| name).collect();
+ for (name, fields) in &hs.records {
+ let list: Vec<String> =
+ fields.iter().map(|f| format!("{}: {}", f.name, f.annotation.as_deref().unwrap_or("?"))).collect();
+ notes.push_str(&format!("- Note: `{name}` is a dataclass/NamedTuple in {} ({}).", hs.file, list.join(", ")));
+ if structs.contains(name) {
+ notes.push_str(&format!(
+ " As a parameter it arrives as the Rust struct `{}` in src/lib.rs.",
+ struct_name(name)
+ ));
+ }
+ if mentions(hs.returns.as_deref(), name) {
+ notes.push_str(&format!(
+ " The result must be a `{name}` too: get the class with `py.import(\"{}\")?.getattr(\"{name}\")?` and call it; verify checks the class and every field.",
+ hs.module.as_deref().unwrap_or_default()
+ ));
+ }
+ notes.push('\n');
+ }
for p in &hs.params {
if let Some(d) = p.default.as_deref().filter(|d| rust_default(d).is_none()) {
notes.push_str(&format!(
@@ -747,6 +867,79 @@ mod tests {
assert!(got("uv run").is_err());
}
+ #[test]
+ fn dataclass_parameters_get_structs() {
+ use crate::hotspot::Param;
+ let field = |name: &str, annotation: &str| Param {
+ name: name.into(),
+ annotation: Some(annotation.into()),
+ ..Param::default()
+ };
+ let mut hs = Hotspot {
+ name: "closest".into(),
+ params: vec![
+ Param { name: "points".into(), annotation: Some("list[Point]".into()), ..Param::default() },
+ Param { name: "box".into(), annotation: Some("Box".into()), ..Param::default() },
+ ],
+ returns: Some("Stats".into()),
+ ..Hotspot::default()
+ };
+ hs.records.insert("Point".into(), vec![field("x", "float"), field("type", "str")]);
+ hs.records.insert("Box".into(), vec![field("lo", "float"), field("hi", "float")]);
+ hs.records.insert("Stats".into(), vec![field("n", "int")]);
+ hs.records.insert("Shape".into(), vec![field("p", "Polygon")]);
+ let lib = lib_rs(&hs, &port());
+ assert!(lib.contains("fn closest(points: Vec<Point>, r#box: PyBox) -> PyResult<Py<PyAny>>"), "{lib}");
+ assert!(lib.contains("struct PyBox {\n lo: f64,\n hi: f64,\n}"), "{lib}");
+ assert!(lib.contains("#[pyo3(attribute(\"type\"))]\n r#type: String,"), "{lib}");
+ assert!(!lib.contains("struct Stats"), "only parameter types get a struct: {lib}");
+
+ let v: Value = serde_json::from_str(r#"{"$obj": ["geo", "Point", [["x", 1.5], ["type", "a"]]]}"#).unwrap();
+ assert_eq!(py_value(&v), r#"Point(x=1.5, type="a")"#);
+ }
+
+ #[test]
+ fn records_round_trip_in_the_runner() {
+ let Some(python) = ["python3", "python"]
+ .into_iter()
+ .find(|p| Command::new(p).arg("--version").output().is_ok_and(|o| o.status.success()))
+ else {
+ eprintln!("no python on PATH, skipping");
+ return;
+ };
+ let dir = std::env::temp_dir().join(format!("fa-records-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ fs::write(dir.join("runner.py"), RUNNER).unwrap();
+ fs::write(
+ dir.join("geo.py"),
+ "from dataclasses import dataclass, field\nfrom typing import NamedTuple\n\n\
+ @dataclass(frozen=True)\nclass P:\n x: float\n y: float\n\n\
+ class B(NamedTuple):\n lo: float\n hi: float\n\n\
+ @dataclass\nclass C:\n n: int\n seen: int = field(init=False, default=0)\n\n\
+ def f(ps: list[P], b: B) -> C:\n return C(len(ps))\n",
+ )
+ .unwrap();
+ let check = "import runpy, sys, os, json\n\
+ d = sys.argv[1]; sys.path.insert(0, d)\n\
+ ns = runpy.run_path(os.path.join(d, 'runner.py'))\n\
+ enc, dec, same, edges, small, variants, describe = (ns[k] for k in ('enc', 'dec', 'same', 'edges', 'small', 'variants', 'describe'))\n\
+ import geo, random\n\
+ c = geo.C(3); object.__setattr__(c, 'seen', 7)\n\
+ for v in (geo.P(1.0, 2.0), geo.B(0.0, 5.0), c, [geo.P(1.0, 2.0)]):\n\
+ \x20 back = dec(json.loads(json.dumps(enc(v))))\n\
+ \x20 assert same(v, back) and type(back) is type(v), (v, back)\n\
+ assert enc(geo.B(0.0, 5.0))['$obj'][:2] == ['geo', 'B']\n\
+ assert not same(geo.B(0.0, 5.0), (0.0, 5.0)) and not same(geo.P(1.0, 2.0), geo.P(1.0, 3.0))\n\
+ b = geo.B(0.0, 5.0)\n\
+ assert edges(b) == [] and small(b) is b and variants(b, random.Random(0)) == []\n\
+ info = describe(os.path.join(d, 'geo.py'), 18, 'f', None, d)\n\
+ assert set(info['records']) == {'P', 'B', 'C'}, info['records']\n\
+ assert info['records']['C'] == [{'name': 'n', 'annotation': 'int'}, {'name': 'seen', 'annotation': 'int'}]\n";
+ let out = Command::new(python).args(["-I", "-c", check]).arg(&dir).output().unwrap();
+ let _ = fs::remove_dir_all(&dir);
+ assert!(out.status.success(), "{}", String::from_utf8_lossy(&out.stderr));
+ }
+
#[test]
fn spots_python() {
assert!(is_python("python"));
diff --git a/src/python/runner.py b/src/python/runner.py
index 2fdec83..013f681 100644
--- a/src/python/runner.py
+++ b/src/python/runner.py
@@ -7,6 +7,7 @@ Modes: profile, record, verify. Not meant to be run by hand.
import ast
import base64
+import dataclasses
import functools
import importlib
import importlib.util
@@ -34,9 +35,33 @@ class Unsupported(Exception):
"""A value that can't be recorded as plain data."""
+def record_fields(v):
+ """Field names of a dataclass or NamedTuple instance, None for anything else."""
+ if isinstance(v, tuple) and isinstance(getattr(type(v), "_fields", None), tuple):
+ return list(type(v)._fields)
+ if dataclasses.is_dataclass(v) and not isinstance(v, type):
+ return [f.name for f in dataclasses.fields(v)]
+ return None
+
+
+# modules recorded classes are looked up in, by the name they were recorded under
+MODULES = {}
+
+
+def find_class(module, qualname):
+ target = MODULES.get(module) or importlib.import_module(module)
+ for part in qualname.split("."):
+ target = getattr(target, part)
+ return target
+
+
def enc(v):
if v is None or isinstance(v, (bool, int, str)):
return v
+ fields = record_fields(v)
+ if fields is not None: # before tuple: a NamedTuple is one
+ cls = type(v)
+ return {"$obj": [cls.__module__, cls.__qualname__, [[f, enc(getattr(v, f))] for f in fields]]}
if isinstance(v, float):
return v if math.isfinite(v) else {"$float": repr(v)}
if isinstance(v, list):
@@ -67,6 +92,17 @@ def dec(v):
return {dec(i) for i in x}
if tag == "$float":
return float(x)
+ if tag == "$obj":
+ module, qualname, fields = x
+ cls = find_class(module, qualname)
+ values = {k: dec(i) for k, i in fields}
+ try:
+ return cls(**values)
+ except TypeError: # fields left out of __init__
+ obj = cls.__new__(cls)
+ for k, i in values.items():
+ object.__setattr__(obj, k, i)
+ return obj
raise ValueError("unknown tag " + tag)
return v
@@ -76,6 +112,9 @@ def same(a, b):
(it prints differently)."""
if isinstance(a, bool) or isinstance(b, bool):
return type(a) is type(b) and a == b
+ fields = record_fields(a)
+ if fields is not None or record_fields(b) is not None:
+ return type(a) is type(b) and all(same(getattr(a, f), getattr(b, f)) for f in fields)
if isinstance(a, float) or isinstance(b, float):
if not (isinstance(a, float) and isinstance(b, float)):
return False
@@ -180,10 +219,28 @@ def parse_file(path):
walk(tree, "", "function")
guard = next((n.lineno for n in tree.body if isinstance(n, ast.If) and is_main_guard(n.test)), None)
- _files[path] = (src, by_line, top, guard)
+ records = {n.name: record_class_fields(n) for n in tree.body
+ if isinstance(n, ast.ClassDef) and is_record_class(n)}
+ _files[path] = (src, by_line, top, guard, records)
return _files[path]
+def is_record_class(node):
+ """@dataclass (or @dataclasses.dataclass(...)) or a NamedTuple subclass."""
+ for d in node.decorator_list:
+ name = dotted(d.func if isinstance(d, ast.Call) else d)
+ if name and name[-1] == "dataclass":
+ return True
+ return any((dotted(b) or [""])[-1] == "NamedTuple" for b in node.bases)
+
+
+def record_class_fields(node):
+ """(name, annotation) of each field, in order; ClassVars aren't fields."""
+ return [(n.target.id, ast.unparse(n.annotation)) for n in node.body
+ if isinstance(n, ast.AnnAssign) and isinstance(n.target, ast.Name)
+ and "ClassVar" not in ast.unparse(n.annotation)]
+
+
def is_main_guard(test):
"""if __name__ == "__main__" (either way round)."""
if not (isinstance(test, ast.Compare) and len(test.ops) == 1 and isinstance(test.ops[0], ast.Eq)):
@@ -227,7 +284,7 @@ def describe(path, line, name, entry, base):
parsed = parse_file(path)
if parsed is None:
return None
- src, by_line, top, guard = parsed
+ src, by_line, top, guard, records = parsed
hit = by_line.get(line)
if hit is None or hit[0].name != name:
return None
@@ -306,9 +363,15 @@ def describe(path, line, name, entry, base):
warnings.append("missing type hints, types are inferred from recorded calls")
factor *= 0.9
+ # dataclasses and NamedTuples from this file that the signature uses, with their fields
+ names = {n.id for p in [node.returns] + [a.annotation for a in positional + args.kwonlyargs] if p is not None
+ for n in ast.walk(p) if isinstance(n, ast.Name)}
+ used = {name: [{"name": f, "annotation": a} for f, a in fields] for name, fields in records.items() if name in names}
+
lines = src.splitlines()
first = min([node.lineno] + [d.lineno for d in node.decorator_list])
return {
+ "records": used,
"qualname": qualname,
"module": module,
"kind": kind,
@@ -462,6 +525,10 @@ def cmd_verify(job, _argv):
sys.modules[spec.name] = entry
spec.loader.exec_module(entry)
module = entry
+ # as in the app, the entry script is __main__: for classes recorded there, and for ports
+ # that look up a class with py.import("__main__")
+ MODULES["__main__"] = entry
+ sys.modules["__main__"] = entry
else:
module = importlib.import_module(job["module"])
original = getattr(getattr(module, job["owner"]) if job.get("owner") else module, job["func"])
@@ -519,7 +586,7 @@ SLICE_LENGTHS = (0, 1, 2, 3, 5, 8, 13, 21, 34, 55)
def variants(value, rng):
"""Smaller versions of a list/str/bytes/tuple argument: empty, tiny, and random slices."""
- if not isinstance(value, (list, tuple, str, bytes)) or len(value) < 2:
+ if not isinstance(value, (list, tuple, str, bytes)) or len(value) < 2 or record_fields(value) is not None:
return []
n = len(value)
out = []
@@ -539,7 +606,7 @@ GROW = (4, 16, 64, 256, 512) # how much bigger, step by step, than the short ve
def edges(value):
"""Inputs where ports and originals tend to part ways, of the same type as the recorded value."""
- if isinstance(value, bool):
+ if isinstance(value, bool) or record_fields(value) is not None:
return []
if isinstance(value, int):
return [x for x in (0, 1, -1) if x != value]
@@ -561,6 +628,8 @@ def edges(value):
def small(value):
"""A short version of a recorded value, so edge cases stay cheap when the real inputs are big."""
+ if record_fields(value) is not None:
+ return value
if isinstance(value, (list, tuple)):
return value[:8]
if isinstance(value, (str, bytes)):
@@ -572,6 +641,8 @@ def bigger(value, factor):
"""The value repeated factor times (None past BIG items or characters)."""
if not isinstance(value, (list, tuple, str, bytes)) or not value or len(value) * factor > BIG:
return None
+ if record_fields(value) is not None:
+ return None
return value * factor