Rewrite your app in Rust, piece by piece, checked against the original at every step. Works with TypeScript, JavaScript, Python, Go, Ruby, Java, C, PHP, C#, Kotlin, PowerShell and Swift.
Rust agent-skillsclaude-codeclicode-migrationcodexffigolangjavajavascriptmcpmigrationnapiperformanceportingpyo3pythonrewriterubyrusttypescript
fix: avoid Python wrapper name clashes (#1489)
Badri Vishal Pandeya1d565902aeb
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 51dcbe71..46f78591 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -17,6 +17,10 @@(`` `rust-anything diff <crate>` shows them ``), and `gate`'s fix for a failed `ported` checknames the crate's `src/port.rs` and `rust-anything gate <crate>`. Before, both left the crateout, so the command failed when run from the repository root (#1485, #1487 by @badrisatyam1-ctrl).+- Python bridge: a function named `error`, `port`, `native_module` or `unpickled_error`, or two+ named `area` and `area_inner`, gives a PyO3 crate that builds. Each `#[pyfunction]` wrapper and+ method is written as `<name>_py` in Rust, so it no longer clashes with the crate's own items;+ Python still calls `shapes.error(3)`, through the unchanged `#[pyo3(name = "error")]` (#1482).- `analyze` maps `laravel/framework` to Laravel Rust (`laravel-rust`, beta), with fit `partial`.Units that import `Illuminate\...` are no longer Blocked with "`laravel/framework` has no Rustequivalent". `analyze --whole-app` on an app whose `composer.json` requires `laravel/framework`diff --git a/src/codegen_py.rs b/src/codegen_py.rsindex 2d0bf595..4ef13c77 100644--- a/src/codegen_py.rs+++ b/src/codegen_py.rs@@ -577,13 +577,13 @@ fn effects_binding(m: &Manifest, f: &PortFn) -> String {format!("\nfn {inner}(py: Python<'_>, {}) -> Result<Py<PyAny>, String> {{\n{body}}}\n\n\/// `{js}`.\n#[pyfunction]\n#[pyo3(name = \"{js}\", signature = ({sig}))]\n\- fn {name}(py: Python<'_>, {}) -> PyResult<Py<PyAny>> {{\n {inner}(py, {}).map_err(error)\n}}\n",+ fn {name}_py(py: Python<'_>, {}) -> PyResult<Py<PyAny>> {{\n {inner}(py, {}).map_err(error)\n}}\n",params.join(", "),py_params(m, &view, params_of(m, &view, None)).join(", "),names.join(", "),js = f.js_name,sig = signature(&view, params_of(m, &view, None)),- name = f.rust_name,+ name = f.rust_name.trim_start_matches("r#"),)}@@ -680,8 +680,8 @@ pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {if f.has_effects() {out.push_str(&effects_binding(m, f));registrations.push(format!(- " m.add_function(wrap_pyfunction!(crate::{}, m)?)?;",- f.rust_name+ " m.add_function(wrap_pyfunction!(crate::{}_py, m)?)?;",+ f.rust_name.trim_start_matches("r#")));continue;}@@ -690,7 +690,9 @@ pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {.iter().map(|(n, t)| format!("{n}: {}", binding_type(t))).collect();- let inner = format!("{}_inner", f.rust_name.trim_start_matches("r#"));+ let base_name = f.rust_name.trim_start_matches("r#");+ let inner = format!("{}_inner", base_name);+ let wrapper = format!("{}_py", base_name);let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();let _ = writeln!(out,@@ -714,15 +716,14 @@ pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {};let _ = writeln!(out,- "fn {}({py_param}{}) -> PyResult<{}> {{",- f.rust_name,+ "fn {wrapper}({py_param}{}) -> PyResult<{}> {{",py_params(m, f, params_of(m, f, None)).join(", "),py_ret(f));let _ = writeln!(out, " {inner}({}){}\n}}", args.join(", "), py_out(f));registrations.push(format!(" m.add_function(wrap_pyfunction!(crate::{}, m)?)?;",- f.rust_name+ wrapper));}for c in &api.classes {@@ -802,13 +803,13 @@ pub fn lib_rs(m: &Manifest, api: &PortApi, modules: &Modules) -> String {} else {sig};+ let method_wrapper = format!("{}_py", method.rust_name.trim_start_matches("r#"));let _ = writeln!(out,- "\n #[pyo3(name = \"{}\", signature = ({}))]\n fn {}({sig}) -> PyResult<{}> {{\n \+ "\n #[pyo3(name = \"{}\", signature = ({}))]\n fn {method_wrapper}({sig}) -> PyResult<{}> {{\n \{snake}_{}_inner({}){}\n }}",method.js_name,signature(method, params_of(m, method, Some(js))),- method.rust_name,py_ret(method),method.rust_name.trim_start_matches("r#"),args.join(", "),@@ -2290,12 +2291,61 @@ mod tests {};let lib = lib_rs(&verdict_manifest(), &api, &modules);assert!(- lib.contains("m.add_function(wrap_pyfunction!(crate::verdict, m)?)?;"),+ lib.contains("m.add_function(wrap_pyfunction!(crate::verdict_py, m)?)?;"),"{lib}");assert!(lib.contains("m.add_class::<crate::Hpdet>()?;"), "{lib}");}+ #[test]+ fn an_export_named_like_a_generated_item_does_not_clash_with_it() {+ let export = |name: &str, ty: &str| PortFn {+ js_name: name.into(),+ rust_name: name.into(),+ params: vec![("n".into(), ty.into())],+ ret: "i64".into(),+ fallible: false,+ is_async: false,+ };+ let api = PortApi {+ functions: vec![+ export("error", "i64"),+ export("port", "i64"),+ export("native_module", "i64"),+ export("unpickled_error", "&mut Vec<i64>"),+ export("area", "i64"),+ export("area_inner", "i64"),+ ],+ ..Default::default()+ };+ let modules = Modules {+ utf16: false,+ js: false,+ };+ let lib = lib_rs(&verdict_manifest(), &api, &modules);+ let mut names: Vec<&str> = lib+ .lines()+ .filter_map(|l| l.strip_prefix("fn ").or_else(|| l.strip_prefix("pub mod ")))+ .map(|l| l.split(['(', ';', '<']).next().unwrap_or(l))+ .collect();+ names.sort_unstable();+ let before = names.len();+ names.dedup();+ assert_eq!(before, names.len(), "{lib}");+ for name in [+ "error",+ "port",+ "native_module",+ "unpickled_error",+ "area_inner",+ ] {+ assert!(+ lib.contains(&format!("#[pyo3(name = \"{name}\", signature")),+ "{lib}"+ );+ }+ }+#[test]fn optional_object_wrapper_accepts_none() {let api = PortApi {@@ -2348,7 +2398,7 @@ mod tests {);assert!(lib.contains(- "fn verdict(py: Python<'_>, readings: Bound<'_, PyAny>, \+ "fn verdict_py(py: Python<'_>, readings: Bound<'_, PyAny>, \#[pyo3(from_py_with = crate::pyconv::given)] thresholds: Option<Bound<'_, PyAny>>)"),"{lib}"diff --git a/tests/pyo3_name.rs b/tests/pyo3_name.rsindex f309b3a2..e3e68874 100644--- a/tests/pyo3_name.rs+++ b/tests/pyo3_name.rs@@ -71,7 +71,7 @@ fn a_crate_named_like_its_export_still_passes_cargo_test() {let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();assert!(- lib.contains("wrap_pyfunction!(crate::slug, m)"),+ lib.contains("wrap_pyfunction!(crate::slug_py, m)"),"the registration is qualified: {lib}");