Skip to content

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.

fix(enable): point to manual wrappers when shadow is unavailable (#1227)

RRFZ92e9e6c44b9a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8eadd874..104160dc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -65,6 +65,8 @@
name of a built-in normalizer (`timestamps=x`). Before, the pattern was saved as given and
matched at every position, so every output was recorded with `[..]` between its characters and
the original failed its own recording (#1205, #1220 by @Alkhanizi-hashem).
+- `enable` points to the generated wrapper for PHP, C# and Swift and gives the same manual switching
+ advice as `shadow` (#1195, #1227 by @Plastic-time).
- `rules` and every agent prompt now read a rule in `RULES.md` whole when it was written by hand:
an indented line under a bullet continues it, `* ` bullets count like `- `, and whitespace is
collapsed as `--add` collapses it. Before, a wrapped rule was cut at its first line, a `* `
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index b8a4604b..cadf4b07 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -170,13 +170,16 @@ rusty_alloc` opts into a pure-Rust allocator instead. Demo: [`demo/x18n-search`]
## Switch a port on and off
+For PHP, C# and Swift, `enable` points to the generated wrapper and explains how to switch
+manually.
+
Every way to switch, in one place:
| What | On | Off |
| --- | --- | --- |
| A TS/JS, Python or PowerShell unit, in place | `rust-anything enable <crate>`: one marked block in each original file rebinds the ported functions to the Rust module, so every caller gets Rust and no import changes. It refuses while a recorded case differs (`--force` skips that check); `go` runs it only after diff and gate pass | `rust-anything disable <crate>`: removes exactly the lines `enable` added, so the files are byte for byte what they were |
| That unit, for one run | (on by default once enabled) | `RUST_ANYTHING_UNIT_<NAME>=original` (`<NAME>` is the crate name without `-rs`, upper case: `RUST_ANYTHING_UNIT_DEDUPE`), or `RUST_ANYTHING_MODE=old` for every unit |
-| A shadow module (any language) | Import it where the app imported the original; `RUST_ANYTHING_MODE=new` runs only Rust | `RUST_ANYTHING_MODE=old`; the default, `shadow`, returns the original's result and compares Rust |
+| A unit with a shadow module | Import it where the app imported the original; `RUST_ANYTHING_MODE=new` runs only Rust | `RUST_ANYTHING_MODE=old`; the default, `shadow`, returns the original's result and compares Rust |
| A unit wired into a front door (`app wire`) | Wired units answer in Rust | `RUST_ANYTHING_UNIT_<NAME>=original` sends that unit's commands to the original |
| An installed package (`package`) | The platform's binary | `RUST_ANYTHING_MODE=old` runs the original it depends on |
@@ -184,7 +187,7 @@ The `enable` block names the crate by a path relative to the source file, so it
of your machine, and it falls back to the original when the module does not load (with
`RUST_ANYTHING_MODE=new` that is an error instead). `record`, `diff`, `bench` and `fuzz` set the
unit's switch to `original` for the original's side, so an enabled unit is still measured
-against the original. Other languages switch through the shadow module.
+against the original.
Every switch is logged. `enable`, `disable`, `app wire`, `app lift` and `go` (when it switches a
unit on) append a line to `rust/audit.jsonl`, and so does every `gate`, passed or failed: the time
diff --git a/src/enable.rs b/src/enable.rs
index 6100e3fc..787a1ae7 100644
--- a/src/enable.rs
+++ b/src/enable.rs
@@ -146,7 +146,7 @@ pub fn enable_only(
)
})?;
let manifest = Manifest::load(&crate_dir)?;
- supported(&manifest)?;
+ supported_in(&crate_dir, &manifest)?;
let selected: Option<Vec<&str>> = match only {
Some(names) => {
let mut unknown = Vec::new();
@@ -642,6 +642,17 @@ pub fn supported(manifest: &Manifest) -> Result<()> {
}
}
+/// Checks whether `enable` supports the crate and points to its wrapper when a manual switch is needed.
+pub fn supported_in(crate_dir: &Path, manifest: &Manifest) -> Result<()> {
+ let crate_dir = crate_dir
+ .canonical()
+ .unwrap_or_else(|_| crate_dir.to_path_buf());
+ if let Some(advice) = crate::shadow::manual_switch_advice(&crate_dir, manifest) {
+ bail!("{advice}");
+ }
+ supported(manifest)
+}
+
fn files(manifest: &Manifest) -> Vec<&str> {
let mut files: Vec<&str> = manifest.exports.iter().map(|f| f.file.as_str()).collect();
files.sort_unstable();
diff --git a/src/main.rs b/src/main.rs
index 9370065b..4f83354d 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1972,9 +1972,9 @@ fn run() -> Result<ExitCode> {
force,
json,
} => {
- // An unsupported crate gets the shadow-module error before any build or diff.
+ // An unsupported crate gets switching advice before any build or diff.
let manifest = bridge::Manifest::load(&crate_dir)?;
- rust_anything::enable::supported(&manifest)?;
+ rust_anything::enable::supported_in(&crate_dir, &manifest)?;
let _lock = rust_anything::fuzz::RecordingLock::take_recovered(&crate_dir)?;
let manifest = bridge::Manifest::load(&crate_dir)?;
// The recording and the cheat guard first, as `gate` reads them: a switch-on must not
diff --git a/src/mcp.rs b/src/mcp.rs
index fbf661fa..a96ac7b2 100644
--- a/src/mcp.rs
+++ b/src/mcp.rs
@@ -1651,7 +1651,7 @@ fn call(name: &str, args: &Value) -> Result<Value> {
"`partial` cannot be combined with `only` or `force`"
);
let manifest = bridge::Manifest::load(&crate_dir)?;
- crate::enable::supported(&manifest)?;
+ crate::enable::supported_in(&crate_dir, &manifest)?;
let _lock = crate::fuzz::RecordingLock::take_recovered(&crate_dir)?;
let manifest = bridge::Manifest::load(&crate_dir)?;
// The recording and the cheat guard first, as `gate` reads them.
diff --git a/src/shadow.rs b/src/shadow.rs
index 1fa0ad7f..5367a04c 100644
--- a/src/shadow.rs
+++ b/src/shadow.rs
@@ -19,6 +19,37 @@ pub struct ShadowOutcome {
pub exports: Vec<String>,
}
+pub(crate) fn manual_switch_advice(crate_dir: &Path, manifest: &Manifest) -> Option<String> {
+ use crate::lang::Lang;
+
+ let 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",
+ crate_dir
+ .join(crate::codegen_php::wrapper_path(manifest))
+ .display()
+ ),
+ 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",
+ crate_dir
+ .join(crate::codegen_swift::wrapper_path(manifest))
+ .display()
+ ),
+ Lang::Csharp => format!(
+ "C# binds calls when it compiles, so there is no shadow module for C# yet; once `diff` \
+ passes, compile {} into the project and call the `<namespace>.Rust` classes (or alias \
+ them with `using`), with the built library next to the app",
+ crate_dir
+ .join(crate::codegen_csharp::wrapper_path(manifest))
+ .display()
+ ),
+ _ => return None,
+ };
+ Some(advice)
+}
+
pub fn shadow(crate_dir: &Path, out: Option<&Path>) -> Result<ShadowOutcome> {
let crate_dir = crate_dir.canonical().with_context(|| {
format!(
@@ -60,14 +91,8 @@ pub fn shadow(crate_dir: &Path, out: Option<&Path>) -> Result<ShadowOutcome> {
exports: manifest.exports.iter().map(|f| f.name.clone()).collect(),
});
}
- if manifest.language == crate::lang::Lang::Php {
- bail!(
- "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",
- crate_dir
- .join(crate::codegen_php::wrapper_path(&manifest))
- .display()
- );
+ if let Some(advice) = manual_switch_advice(&crate_dir, &manifest) {
+ bail!("{advice}");
}
if manifest.language == crate::lang::Lang::Powershell {
bail!(
@@ -79,25 +104,6 @@ pub fn shadow(crate_dir: &Path, out: Option<&Path>) -> Result<ShadowOutcome> {
.display()
);
}
- if manifest.language == crate::lang::Lang::Swift {
- bail!(
- "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",
- crate_dir
- .join(crate::codegen_swift::wrapper_path(&manifest))
- .display()
- );
- }
- if manifest.language == crate::lang::Lang::Csharp {
- bail!(
- "C# binds calls when it compiles, so there is no shadow module for C# yet; once `diff` \
- passes, compile {} into the project and call the `<namespace>.Rust` classes (or alias \
- them with `using`), with the built library next to the app",
- crate_dir
- .join(crate::codegen_csharp::wrapper_path(&manifest))
- .display()
- );
- }
if manifest.language == crate::lang::Lang::Ruby {
let path = match out {
Some(p) => p.to_path_buf(),
diff --git a/tests/switch.rs b/tests/switch.rs
index a52450fd..fa4d77cb 100644
--- a/tests/switch.rs
+++ b/tests/switch.rs
@@ -672,6 +672,85 @@ fn disable_after_enable_only_a_multibyte_name_restores_the_file() {
std::fs::remove_dir_all(root).unwrap();
}
+#[test]
+fn enable_on_a_crate_without_shadow_names_the_generated_wrapper() {
+ let fixtures = [
+ (
+ "sum.php",
+ "<?php\nfunction add(int $a, int $b): int { return $a + $b; }\n",
+ "php/sum_rs.php",
+ "require",
+ ),
+ (
+ "Sum.cs",
+ "public static class Sum { public static int Add(int a, int b) => a + b; }\n",
+ "cs/SumRs.cs",
+ "compile",
+ ),
+ (
+ "sum.swift",
+ "public func add(_ a: Int, _ b: Int) -> Int { a + b }\n",
+ "swift/SumRs.swift",
+ "compile",
+ ),
+ ];
+
+ for (unit, source, wrapper, verb) in fixtures {
+ let project = common::Scratch::new(std::env::temp_dir().join(format!(
+ "rust-anything-switch-wrapper-{}-{unit}",
+ std::process::id()
+ )));
+ std::fs::write(project.0.join(unit), source).unwrap();
+ let dir = project.0.join("custom port");
+ bridge::bridge(&bridge::Options {
+ root: &project.0,
+ unit,
+ kind: None,
+ out: Some(dir.clone()),
+ name: Some("sum-rs".into()),
+ force: false,
+ keep: vec![],
+ lang: None,
+ batch: vec![],
+ as_json: vec![],
+ allocator: Default::default(),
+ })
+ .unwrap();
+
+ let expected = dir.canonical().unwrap().join(wrapper);
+ assert!(expected.is_file(), "missing {}", expected.display());
+ let enable = common::cli().arg("enable").arg(&dir).output().unwrap();
+ let shadow = common::cli().arg("shadow").arg(&dir).output().unwrap();
+ assert!(!enable.status.success(), "{enable:?}");
+ assert!(!shadow.status.success(), "{shadow:?}");
+ let advice = format!("{verb} {}", expected.display());
+ let enabled = String::from_utf8(enable.stderr).unwrap();
+ assert!(enabled.contains(&advice), "{unit}: {enabled}");
+ assert_eq!(enabled, String::from_utf8(shadow.stderr).unwrap());
+
+ let library = enable::enable(&dir).unwrap_err().to_string();
+ assert!(library.contains(&advice), "{unit}: {library}");
+ let manifest = bridge::Manifest::load(&dir).unwrap();
+ let old_api = enable::supported(&manifest).unwrap_err().to_string();
+ assert!(
+ old_api.contains("use the shadow module"),
+ "{unit}: {old_api}"
+ );
+
+ let response = rust_anything::mcp::handle(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": "enable", "arguments": { "crate": dir } },
+ }))
+ .unwrap();
+ let result = &response["result"];
+ assert_eq!(result["isError"], true, "{response}");
+ let message = result["content"][0]["text"].as_str().unwrap();
+ assert!(message.contains(&advice), "{unit}: {message}");
+ }
+}
+
#[test]
fn enable_on_a_go_crate_says_use_the_shadow_module_before_any_build() {
let root = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/go");