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(bridge): name kept functions in the PHP, Swift and C cut-over advice (#1198) (#1240)
Bora Ata Türkoğlu5d97aafac8b2
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 29db508b..93eec376 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,13 @@## Unreleased+- PHP, Swift and C: when a unit has functions that stay in the original language (a variadic one,+ one with a pointer parameter, one named with `--keep`), the cut-over advice names them and says+ to move them out of the original file first: in the crate's README and the wrapper's header for+ PHP and Swift, in the `shadow` refusal, and in what `bridge` prints for C. Before, the advice+ was to load the wrapper (or link the library) in place of the original, which also removed the+ kept functions from the app: PHP failed with `Call to undefined function`, Swift did not compile+ and C did not link (#1198, #1240 by @boracomet).- On Linux, checking whether a port is free no longer opens a listener. While another thread wasstarting a process, such a listener could stay open after the check, so the server then startedon that port failed with `Address already in use`, or a client got `Connection reset by peer`diff --git a/docs/languages.md b/docs/languages.mdindex 9cd2a812..326ff6ff 100644--- a/docs/languages.md+++ b/docs/languages.md@@ -66,7 +66,9 @@ so it replaces the original file rather than joining it. Whatever else that filealong: a class the bridge keeps in PHP (an instance method, a non-final class or an unsupporteddefault, say), functions the bridge keeps in PHP (a `callable` or `Closure` parameter, say), andtop-level statements such as `define('FEATURE_ENABLED', true)` are not in the wrapper, and-requiring both files redeclares the bridged functions. Keep those in a file that stays required.+requiring both files redeclares the bridged functions. Keep those in a file that stays required:+the crate's README, the wrapper's header and the `shadow` refusal name the kept functions and the+files to move them out of.Eachcall crosses as JSON, about 1 µs, so `bench` shows small functions slower than PHP; there is no `shadow` for PHP yet([issue #200](https://github.com/erkamyaman/rust-anything/issues/200)).@@ -108,7 +110,9 @@ text form of a `Double`. A file's top-level functions with `String`, integer, `Da C module map (`swiftc` on PATH to record and diff; Xcode or a Swift 5.9+ toolchain). Once `diff`passes, compile the generated `swift/<Crate>.swift` (`foo-rs` gives `swift/FooRs.swift`) into thetarget in place of the original file, with `-I swift` for the module map in-`swift/<Crate>Native/` and `-L swift` for the built library. The crate builds with+`swift/<Crate>Native/` and `-L swift` for the built library. A function kept in Swift (a variadic+one, say) is not in the wrapper: the crate's README and the wrapper's header name it, and it has to+move out of the original file into one that stays in the target first. The crate builds with`overflow-checks = true`, so a port's `+` panics where Swift traps, and the wrapper turns a Rustpanic into `fatalError`: `diff` compares a trap with a trap. A port's `Err("Type: message")` isthrown as `<Crate>Error` with that type name and message, and `diff` compares both with thediff --git a/src/bridge.rs b/src/bridge.rsindex e5441704..36118d20 100644--- a/src/bridge.rs+++ b/src/bridge.rs@@ -2647,6 +2647,11 @@ fn bridge_c(for j in kept {notes.push(format!("`{}` stays in C: {}.", j.name, j.reason));}+ // Issue #1198: the library has the bridged functions only, and the C objects it replaces+ // also hold what stays.+ if let Some(note) = kept_cut_over(kept, "C", Some("link the Rust library")) {+ notes.push(format!("{note}."));+ }Ok(Outcome {crate_dir: crate_dir.to_path_buf(),kind: Kind::CAbi,@@ -2656,6 +2661,65 @@ fn bridge_c(})}+/// `a`, `b` and `c`: each item once, in backticks, in the order given.+fn backticked(items: impl Iterator<Item = impl AsRef<str>>) -> (String, usize) {+ let mut seen: Vec<String> = Vec::new();+ for item in items {+ let item = format!("`{}`", item.as_ref());+ if !seen.contains(&item) {+ seen.push(item);+ }+ }+ let text = match seen.split_last() {+ Some((last, rest)) if !rest.is_empty() => format!("{} and {last}", rest.join(", ")),+ _ => seen.concat(),+ };+ (text, seen.len())+}++/// What to do about the functions that stay in the original language where the generated wrapper+/// (PHP, Swift) or library (C) takes the place of the original file: it defines the bridged+/// functions only, so what stays has to move out of that file first, or it is gone from the app+/// (issue #1198). `step` is what the user does next ("require `php/x.php`"); without one the+/// sentence ends in "first". Nothing kept gives `None`.+pub fn kept_cut_over(kept: &[JsOnly], original: &str, step: Option<&str>) -> Option<String> {+ if kept.is_empty() {+ return None;+ }+ let (names, count) = backticked(kept.iter().map(|j| &j.name));+ let (files, file_count) = backticked(kept.iter().map(|j| &j.file));+ let (stays, it) = if count == 1 {+ ("stays", "it")+ } else {+ ("stay", "them")+ };+ let (a_file, place) = if file_count == 1 {+ ("a file", "its place")+ } else {+ ("files", "their place")+ };+ let end = match step {+ Some(step) => format!("before you {step} in {place}"),+ None => "first".into(),+ };+ Some(format!(+ "{names} {stays} in {original}: move {it} out of {files} into {a_file} you keep {end}"+ ))+}++/// The line a PHP or Swift wrapper's header gets for [`kept_cut_over`]: the names that stay in+/// the original, so it is visible in the file that replaces it. Empty when nothing stays.+pub fn kept_header(kept: &[JsOnly], original: &str) -> String {+ if kept.is_empty() {+ return String::new();+ }+ let (names, _) = backticked(kept.iter().map(|j| &j.name));+ format!(+ "// Kept in {original} and not defined here: {names}. Move what is kept out of the original \+ before this file replaces it.\n"+ )+}+fn readme(m: &Manifest) -> String {use crate::lang::Lang;let section = |heading: &str, items: Vec<(&str, &str, u32)>| -> String {@@ -2706,10 +2770,20 @@ fn readme(m: &Manifest) -> String {Lang::Php | Lang::Csharp | Lang::Powershell | Lang::Swift => String::new(),_ => "rust-anything shadow . # run both in the app, log mismatches\n".into(),};+ // Issue #1198: the wrapper replaces the original file, so what stays there has to move first.+ let kept_step = |step: &str| -> String {+ kept_cut_over(&m.js_only, original, Some(step))+ .map(|note| format!("{note}.\n"))+ .unwrap_or_default()+ };let switch = match m.language {Lang::Php => format!(- "\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n",- crate::codegen_php::wrapper_path(m)+ "\nPHP has no shadow module: once `diff` passes, require `{}` in place of the original files.\n{}",+ crate::codegen_php::wrapper_path(m),+ kept_step(&format!(+ "require `{}`",+ crate::codegen_php::wrapper_path(m)+ ))),Lang::Powershell => format!("\nPowerShell has no shadow module: once `diff` passes, `rust-anything enable .` \@@ -2727,8 +2801,12 @@ fn readme(m: &Manifest) -> String {"\nSwift has no shadow module: once `diff` passes, compile `{}` into the target in place \of the original file, with `swift/` on the import path (`-I swift`) and the built \library on the link path (`-L swift`). A Rust panic stops the program, as a Swift \- trap does.\n",- crate::codegen_swift::wrapper_path(m)+ trap does.\n{}",+ crate::codegen_swift::wrapper_path(m),+ kept_step(&format!(+ "compile `{}`",+ crate::codegen_swift::wrapper_path(m)+ ))),_ => String::new(),};@@ -3517,6 +3595,64 @@ mod tests {assert!(!php.contains("rust-anything shadow") && php.contains("PHP has no shadow module"));}+ #[test]+ fn the_cut_over_line_names_what_stays_in_the_original() {+ // Issue #1198: the wrapper replaces the original file, so a function kept there goes with it.+ let manifest = |language: &str, unit: &str, kept: &[(&str, &str)]| -> Manifest {+ let js_only: Vec<String> = kept+ .iter()+ .map(|(name, file)| {+ format!(+ r#"{{"name": "{name}", "file": "{file}", "line": 3, "reason": "variadic"}}"#+ )+ })+ .collect();+ serde_json::from_str(&format!(+ r#"{{"schema": "rust-anything/bridge@1", "root": ".", "unit": "{unit}", "language": "{language}", "kind": "ffi", "crate_name": "text-rs", "exports": [], "js_only": [{}]}}"#,+ js_only.join(", ")+ ))+ .unwrap()+ };+ let php = readme(&manifest(+ "php",+ "src/text.php",+ &[("total", "src/text.php")],+ ));+ assert!(+ php.contains(+ "`total` stays in PHP: move it out of `src/text.php` into a file you keep before \+ you require `php/text_rs.php` in its place.\n"+ ),+ "{php}"+ );+ let swift = readme(&manifest(+ "swift",+ "Sources/Text",+ &[+ ("total", "Sources/Text/Calc.swift"),+ ("mean", "Sources/Text/Calc.swift"),+ ("join", "Sources/Text/Words.swift"),+ ],+ ));+ assert!(+ swift.contains(+ "`total`, `mean` and `join` stay in Swift: move them out of \+ `Sources/Text/Calc.swift` and `Sources/Text/Words.swift` into files you keep \+ before you compile `swift/TextRs.swift` in their place.\n"+ ),+ "{swift}"+ );+ // Nothing kept: the line is as it was.+ for (language, unit) in [("php", "src/text.php"), ("swift", "Sources/Text")] {+ let plain = readme(&manifest(language, unit, &[]));+ assert!(plain.contains("has no shadow module"), "{plain}");+ assert!(!plain.contains("move"), "{plain}");+ }+ // A language with a shadow module re-exports what stays, so it gets no such line.+ let ts = readme(&manifest("ts", "src/text.ts", &[("total", "src/text.ts")]));+ assert!(ts.contains("## Kept in TS") && !ts.contains("move"), "{ts}");+ }+fn local_type(name: &str, text: &str) -> LocalType {LocalType {name: name.into(),diff --git a/src/codegen_php.rs b/src/codegen_php.rsindex 6d09f2fc..947218de 100644--- a/src/codegen_php.rs+++ b/src/codegen_php.rs@@ -161,6 +161,8 @@ fn response_var(f: &ExportedFn) -> String {pub fn wrapper(m: &Manifest, api: &crate::codegen::PortApi) -> String {let (dylib, dll, so) = library_names(m);let class = native_class(m);+ // Issue #1198: what stays in PHP is not in this file, which replaces the original.+ let kept = crate::bridge::kept_header(&m.js_only, "PHP");let mut out = format!("<?php\n\n\// The Rust port of `{unit}`, generated by rust-anything: the same functions and static\n\@@ -168,7 +170,8 @@ pub fn wrapper(m: &Manifest, api: &crate::codegen::PortApi) -> String {// of the original files it bridges; classes kept in PHP stay in their own files.\n\// Outside the CLI, PHP allows FFI only with ffi.enable=true in php.ini: the default,\n\// \"preload\", allows it in the CLI and in preloaded scripts only.\n\- // Regenerate with `rust-anything refresh`.\n\n\+ // Regenerate with `rust-anything refresh`.\n\+ {kept}\n\{CODEC_PHP}\n\namespace RustAnything {{\n \final class {class}\n {{\n \@@ -609,6 +612,39 @@ mod tests {);}+ #[test]+ fn the_header_names_what_stays_in_php() {+ // Issue #1198: the wrapper is required in place of the original, which also holds these.+ let mut m = manifest();+ let header = |m: &Manifest| -> String {+ let w = wrapper(m, &Default::default());+ w.split("namespace ").next().unwrap_or_default().to_string()+ };+ assert!(!header(&m).contains("Kept in PHP"), "{}", header(&m));+ m.js_only = vec![+ crate::bridge::JsOnly {+ name: "total".into(),+ file: "src/text.php".into(),+ line: 3,+ reason: "takes `...$args`".into(),+ },+ crate::bridge::JsOnly {+ name: "each".into(),+ file: "src/text.php".into(),+ line: 9,+ reason: "takes a callback".into(),+ },+ ];+ assert!(+ header(&m).contains(+ "// Kept in PHP and not defined here: `total` and `each`. Move what is kept out of the \+ original before this file replaces it.\n"+ ),+ "{}",+ header(&m)+ );+ }+#[test]fn static_methods_are_written_as_a_class() {let mut m = manifest();diff --git a/src/codegen_swift.rs b/src/codegen_swift.rsindex f93e219b..13a30656 100644--- a/src/codegen_swift.rs+++ b/src/codegen_swift.rs@@ -448,11 +448,14 @@ fn signatures(m: &Manifest) -> Vec<(&crate::ts::exports::ExportedFn, SwiftSig)>pub fn wrapper(m: &Manifest) -> String {let native = native_module(m);let error = error_type(m);+ // Issue #1198: what stays in Swift is not in this file, which replaces the original.+ let kept = crate::bridge::kept_header(&m.js_only, "Swift");let mut out = format!("// The Rust port of `{unit}`, generated by rust-anything: the same functions, with the same\n\// labels, defaults and `throws`, each calling the Rust library through the C module\n\// `{native}` (in `swift/{native}/`). Compile it into the target in place of the original\n\- // file. Regenerate with `rust-anything refresh`.\n\n\+ // file. Regenerate with `rust-anything refresh`.\n\+ {kept}\n\import {native}\n\n\/// An error a Rust port returned: `Err(\"Type: message\")` arrives as `typeName` and\n\/// `message`.\n\@@ -691,6 +694,31 @@ mod tests {}}+ #[test]+ fn the_header_names_what_stays_in_swift() {+ // Issue #1198: the wrapper is compiled in place of the original, which also holds these.+ let mut m = manifest(&[("add", "add(_ a: Int, _ b: Int) -> Int")]);+ let header = |m: &Manifest| -> String {+ let w = wrapper(m);+ w.split("import ").next().unwrap_or_default().to_string()+ };+ assert!(!header(&m).contains("Kept in Swift"), "{}", header(&m));+ m.js_only = vec![crate::bridge::JsOnly {+ name: "total".into(),+ file: "Sources/Geo/Geo.swift".into(),+ line: 3,+ reason: "takes a variadic parameter `xs`".into(),+ }];+ assert!(+ header(&m).contains(+ "// Kept in Swift and not defined here: `total`. Move what is kept out of the original \+ before this file replaces it.\n"+ ),+ "{}",+ header(&m)+ );+ }+#[test]fn an_array_of_unsigned_integers_keeps_its_range_too() {// Review of #1085: `[UInt64]` matched nothing, so the port took `Vec<i64>`.diff --git a/src/shadow.rs b/src/shadow.rsindex 5367a04c..cb332f3c 100644--- a/src/shadow.rs+++ b/src/shadow.rs@@ -25,17 +25,19 @@ pub(crate) fn manual_switch_advice(crate_dir: &Path, manifest: &Manifest) -> Optlet advice = match manifest.language {Lang::Php => format!("PHP cannot redefine a function once the original is loaded, so there is no shadow \- module for PHP yet; once `diff` passes, require {} in place of the original files",+ module for PHP yet; once `diff` passes, require {} in place of the original files{}",crate_dir.join(crate::codegen_php::wrapper_path(manifest))- .display()+ .display(),+ kept_first(manifest)),Lang::Swift => format!("Swift binds calls when it compiles, so there is no shadow module for Swift yet; once \- `diff` passes, compile {} into the target in place of the original file",+ `diff` passes, compile {} into the target in place of the original file{}",crate_dir.join(crate::codegen_swift::wrapper_path(manifest))- .display()+ .display(),+ kept_first(manifest)),Lang::Csharp => format!("C# binds calls when it compiles, so there is no shadow module for C# yet; once `diff` \@@ -410,6 +412,14 @@ pub fn shadow(crate_dir: &Path, out: Option<&Path>) -> Result<ShadowOutcome> {/// Makes the shadow honor the unit's kill switch, `RUST_ANYTHING_UNIT_<NAME>=original`, before/// `RUST_ANYTHING_MODE`: the original package can send one unit back on its own.+/// What a refusal adds when the wrapper it points to leaves out functions that stay in the+/// original file (issue #1198); empty when none stay.+fn kept_first(manifest: &Manifest) -> String {+ crate::bridge::kept_cut_over(&manifest.js_only, manifest.language.name(), None)+ .map(|note| format!("; {note}"))+ .unwrap_or_default()+}+fn with_kill_switch(text: &str, crate_name: &str) -> String {let switch = crate::front_door::kill_switch(crate_name);text.replacen(@@ -740,6 +750,33 @@ mod tests {(root, crate_dir)}+ #[test]+ fn the_php_refusal_names_what_stays_in_php() {+ // Issue #1198: requiring the wrapper in place of the original drops what stayed there.+ let source = "<?php\nfunction slugify(string $s): string { return strtolower($s); }\n\+ function total(int ...$xs): int { return array_sum($xs); }\n";+ let (root, crate_dir) = bridged("php-kept", "text.php", source);+ let refused = super::shadow(&crate_dir, None).unwrap_err().to_string();+ assert!(refused.contains("no shadow module for PHP"), "{refused}");+ assert!(+ refused.contains(+ "in place of the original files; `total` stays in PHP: move it out of `text.php` \+ into a file you keep first"+ ),+ "{refused}"+ );+ let _ = std::fs::remove_dir_all(root);++ let source = "<?php\nfunction slugify(string $s): string { return strtolower($s); }\n";+ let (root, crate_dir) = bridged("php-none-kept", "text.php", source);+ let refused = super::shadow(&crate_dir, None).unwrap_err().to_string();+ assert!(+ refused.ends_with("in place of the original files"),+ "{refused}"+ );+ let _ = std::fs::remove_dir_all(root);+ }+fn python() -> Option<&'static str> {["python3", "python"].into_iter().find(|p| {std::process::Command::new(p)