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.
Rust agent-skillsai-agentsclaude-codeclaude-code-plugincodexdeveloper-toolsffimcpmcp-servernapi-rsnodejsoptimizationperformanceprofilerpyo3pythonrewrite-it-in-rustrubyrusttypescript
python: verify tells tuples from lists (#60)
Vaibhav P.07bd81d11cb2
diff --git a/src/python.rs b/src/python.rsindex c56e3db..775bf0d 100644--- a/src/python.rs+++ b/src/python.rs@@ -188,6 +188,16 @@ pub fn rust_type(annotation: &str, owned: bool) -> Option<String> {/// 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> {+ rust_type_at(annotation, owned, false, known)+}++/// `returned`: a tuple[T, ...] in the result has to stay a tuple, and a Vec would come back as a list.+fn rust_type_at(+ annotation: &str,+ owned: bool,+ returned: 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]| {@@ -196,7 +206,7 @@ fn rust_type_in(annotation: &str, owned: bool, known: &dyn Fn(&str) -> Option<St.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_in(x, owned, known).map(|t| format!("Option<{t}>"));+ return rust_type_at(x, owned, returned, known).map(|t| format!("Option<{t}>"));}Some(match a {"int" => "i64".into(),@@ -220,13 +230,17 @@ fn rust_type_in(annotation: &str, owned: bool, known: &dyn Fn(&str) -> Option<Stformat!("numpy::PyReadonlyArrayDyn<'_, {elem}>")}} else if let Some(x) = inner(&["list", "List", "Sequence"]) {- format!("Vec<{}>", rust_type_in(x, true, known)?)+ format!("Vec<{}>", rust_type_at(x, true, returned, known)?)} else if let Some(x) = inner(&["tuple", "Tuple"]) {let raw_parts = split_top(x);- if raw_parts.len() == 2 && raw_parts[1].trim() == "..." {+ let any_length = raw_parts.len() == 2 && raw_parts[1].trim() == "...";+ if any_length && returned {+ "Py<pyo3::types::PyTuple>".into()+ } else if any_length {format!("Vec<{}>", rust_type_in(&raw_parts[0], true, known)?)} else {- let parts: Option<Vec<String>> = raw_parts.iter().map(|p| rust_type_in(p, true, known)).collect();+ let parts: Option<Vec<String>> =+ raw_parts.iter().map(|p| rust_type_at(p, true, returned, known)).collect();let parts = parts?;if parts.iter().any(|p| p == "...") {return None;@@ -241,7 +255,7 @@ fn rust_type_in(annotation: &str, owned: bool, known: &dyn Fn(&str) -> Option<Stformat!("std::collections::HashMap<{}, {}>",rust_type_in(&kv[0], true, known)?,- rust_type_in(&kv[1], true, known)?+ rust_type_at(&kv[1], true, returned, known)?)} else {let x = inner(&["set", "Set", "frozenset"])?;@@ -470,7 +484,7 @@ fn record_structs(hs: &Hotspot) -> Vec<(String, String)> {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+ let mut params: Vec<String> = hs.params.iter().map(|p| {@@ -502,7 +516,11 @@ pub fn lib_rs(hs: &Hotspot, port: &Port) -> String {} else {String::new()};- let ret = hs.returns.as_deref().and_then(|a| rust_type(a, true)).unwrap_or_else(|| "Py<PyAny>".into());+ let ret =+ hs.returns.as_deref().and_then(|a| rust_type_at(a, true, true, &known)).unwrap_or_else(|| "Py<PyAny>".into());+ if ret.contains("PyTuple") {+ params.insert(0, "py: Python<'_>".into());+ }format!("//! Rust port of {id} ({file}:{line}), generated by fast-anything.\n\//! Replace the todo!() with a faithful, fast port. TASK.md has the original and real calls.\n\@@ -937,6 +955,21 @@ mod tests {assert!(lib.contains("fn join_words(a: i64, b: i64)"), "{lib}");}+ #[test]+ fn tuple_returns_stay_tuples() {+ for (returns, want) in [+ ("tuple[int, ...]", "(py: Python<'_>) -> PyResult<Py<pyo3::types::PyTuple>>"),+ ("typing.Tuple[str, ...]", "-> PyResult<Py<pyo3::types::PyTuple>>"),+ ("tuple[int, ...] | None", "-> PyResult<Option<Py<pyo3::types::PyTuple>>>"),+ ("list[tuple[int, ...]]", "-> PyResult<Vec<Py<pyo3::types::PyTuple>>>"),+ ("tuple[int, float]", "-> PyResult<(i64, f64)>"),+ ("list[tuple[int, int]]", "-> PyResult<Vec<(i64, i64)>>"),+ ] {+ let lib = lib_rs(&Hotspot { returns: Some(returns.into()), ..Hotspot::default() }, &port());+ assert!(lib.contains(want), "{lib}");+ }+ }+#[test]fn verify_tells_ints_from_floats() {let Some(python) = ["python3", "python"]@@ -953,7 +986,8 @@ mod tests {assert not same(3.0, 3) and not same(3, 3.0)\n\assert not same([1.5, 2.0], [1.5, 2])\n\assert not same({'k': 2.0}, {'k': 2})\n\- assert same(3.0, 3.0 + 1e-12) and same(3, 3) and same((1.0, 2), [1.0, 2])\n\+ assert same(3.0, 3.0 + 1e-12) and same(3, 3) and same((1.0, 2), (1.0, 2))\n\+ assert not same((1, 2), [1, 2]) and not same([(1, 2)], [[1, 2]])\n\assert same(float('nan'), float('nan')) and not same(True, 1)\n";let out = Command::new(python).args(["-I", "-c", check]).arg(&runner).output().unwrap();let _ = fs::remove_file(&runner);diff --git a/src/python/runner.py b/src/python/runner.pyindex 54caa63..daa4ac3 100644--- a/src/python/runner.py+++ b/src/python/runner.py@@ -136,8 +136,8 @@ def dec(v):def same(a, b):- """Equality the way a caller would see it: list == tuple, floats within 1e-9, but 3 != 3.0- (it prints differently)."""+ """Equality the way a caller would see it: floats within 1e-9, but 3 != 3.0 (it prints+ differently) and a list isn't a tuple (it can't be hashed)."""np = sys.modules.get("numpy")if np is not None:if isinstance(a, np.ndarray) or isinstance(b, np.ndarray):@@ -161,6 +161,8 @@ def same(a, b):return math.isnan(a) and math.isnan(b)return math.isclose(a, b, rel_tol=1e-9, abs_tol=1e-12)if isinstance(a, (list, tuple)) and isinstance(b, (list, tuple)):+ if isinstance(a, tuple) != isinstance(b, tuple):+ return Falsereturn len(a) == len(b) and all(same(x, y) for x, y in zip(a, b))if isinstance(a, dict) and isinstance(b, dict):return a.keys() == b.keys() and all(same(a[k], b[k]) for k in a)