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(refresh): say when a pub fn is not an export, and keep its Rust name in Python and Ruby (#1232)

Orca71a0e423c02d
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9e633907..9593f186 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -91,6 +91,12 @@
- The MCP `bridge` tool describes the generated bindings for every supported language. Its `unit`
description and `bridge --help` also mention bridging a single source file (#1199, #1223 by
@Plastic-time).
+- `refresh` prints a line for each `pub fn` in `port.rs` that matches no export of the original,
+ since it is now part of the bridged API: "`helper_extra` is not an export of `mathx.py` and is
+ now part of the bridged API; make it private (`fn`) if it is a helper". The MCP `refresh` result
+ lists them in `not_exports`. In a Python or Ruby crate such a function keeps its Rust name,
+ `helper_extra`. Before, it was bound as `helperExtra`, a name no Python or Ruby caller writes,
+ and showed up only in the "Regenerated ... for ..." list (#1200, #1232 by @og-orca).
- `docs/STATUS.md`, `CONTRIBUTING.md` and the site's PHP and C# pages say the macOS CI job
installs and requires PHP, .NET and Kotlin, so their tests run in CI there and skip on Linux and
Windows. Before, they said no CI job installed them (#1209, #1219 by @Alkhanizi-hashem).
diff --git a/src/bridge.rs b/src/bridge.rs
index 2343cdeb..e5441704 100644
--- a/src/bridge.rs
+++ b/src/bridge.rs
@@ -1692,8 +1692,13 @@ fn loader_file(m: &Manifest, api: &codegen::PortApi) -> (String, String) {
}
/// A port function whose doc line does not name an export (`/// Port of \`Integer.toString\``)
-/// takes the name of the export it was generated for, matched by its Rust name.
+/// takes the name of the export it was generated for, matched by its Rust name. One that matches
+/// no export and has no doc name keeps its Rust name in Python and Ruby, whose callers write
+/// snake_case, instead of the camelCase default. Python's loader has `_names` of its own, so a
+/// helper named like one keeps the default there.
pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
+ let python = m.language == crate::lang::Lang::Python;
+ let snake = python || m.language == crate::lang::Lang::Ruby;
for f in &mut api.functions {
if m.exports.iter().any(|e| e.name == f.js_name) {
continue;
@@ -1705,15 +1710,32 @@ pub fn match_export_names(m: &Manifest, api: &mut codegen::PortApi) {
.find(|e| snake_case(&e.name).trim_start_matches("r#") == rust)
{
f.js_name = e.name.clone();
+ } else if snake
+ && !api.doc_named.contains(&f.rust_name)
+ && !(python && rust.starts_with('_'))
+ {
+ f.js_name = rust.to_string();
}
}
}
+/// The Rust names of the port functions that match no export of the original.
+fn not_exports(m: &Manifest, api: &codegen::PortApi) -> Vec<String> {
+ api.functions
+ .iter()
+ .filter(|f| !m.exports.iter().any(|e| e.name == f.js_name))
+ .map(|f| f.rust_name.clone())
+ .collect()
+}
+
/// What `refresh` rewrote.
#[derive(Debug, Serialize)]
pub struct Refreshed {
pub functions: Vec<String>,
pub files: Vec<String>,
+ /// Bound functions that match no export of the original, by Rust name: a `pub` helper in
+ /// `port.rs` that is now part of the bridged API.
+ pub not_exports: Vec<String>,
}
/// Regenerates the binding layer (`lib.rs`, `index.cjs`, `js.rs`) from the signatures in
@@ -1735,6 +1757,7 @@ pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
return Ok(Refreshed {
functions: manifest.exports.iter().map(|f| f.name.clone()).collect(),
files: files.into_iter().map(|(p, _)| p).collect(),
+ not_exports: Vec::new(),
});
}
if manifest.kind == Kind::Ffi {
@@ -1758,6 +1781,7 @@ pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
return Ok(Refreshed {
functions: api.functions.iter().map(|f| f.js_name.clone()).collect(),
files: files.into_iter().map(|(p, _)| p).collect(),
+ not_exports: not_exports(&manifest, &api),
});
}
let port =
@@ -1806,6 +1830,7 @@ pub fn refresh(crate_dir: &Path) -> Result<Refreshed> {
.chain(fns.classes.iter().map(|c| format!("class {}", c.js_name)))
.collect(),
files: files.into_iter().map(|(p, _)| p).collect(),
+ not_exports: not_exports(&manifest, &fns),
})
}
diff --git a/src/codegen.rs b/src/codegen.rs
index bf544304..c3272de3 100644
--- a/src/codegen.rs
+++ b/src/codegen.rs
@@ -47,6 +47,8 @@ pub struct PortApi {
pub structs: Vec<String>,
/// The structs whose `impl` has a `pub fn rank` (an index that ranks by itself).
pub ranked: Vec<String>,
+ /// The functions, by Rust name, that a `/// Port of` line names.
+ pub doc_named: Vec<String>,
/// Whether `port.rs` mentions `serde_json` or `Value`.
pub uses_json_value: bool,
}
@@ -346,8 +348,14 @@ pub fn is_async(f: &ExportedFn) -> bool {
/// documented `/// Port of class `Name``, with an `impl` holding `new` and its methods.
pub fn parse_port(source: &str) -> PortApi {
let lines: Vec<&str> = source.lines().collect();
+ let functions = functions_in(&lines, "");
let mut api = PortApi {
- functions: functions_in(&lines, ""),
+ doc_named: functions
+ .iter()
+ .filter(|(_, named)| *named)
+ .map(|(f, _)| f.rust_name.clone())
+ .collect(),
+ functions: functions.into_iter().map(|(f, _)| f).collect(),
classes: Vec::new(),
structs: lines
.iter()
@@ -403,7 +411,7 @@ pub fn parse_port(source: &str) -> PortApi {
let block = &lines[start + 1..end];
let mut constructor = None;
let mut methods = Vec::new();
- for f in functions_in(block, " ") {
+ for (f, _) in functions_in(block, " ") {
if f.rust_name == "new" {
constructor = Some(f);
} else {
@@ -509,8 +517,8 @@ fn doc_name(before: &[&str], prefix: &str) -> Option<String> {
}
/// `pub fn` items at one indentation level. In an `impl`, `Port of `Class.method`` names the
-/// method `method`.
-fn functions_in(lines: &[&str], indent: &str) -> Vec<PortFn> {
+/// method `method`. Each comes with whether such a line names it.
+fn functions_in(lines: &[&str], indent: &str) -> Vec<(PortFn, bool)> {
let mut out = Vec::new();
let mut i = 0;
while i < lines.len() {
@@ -533,8 +541,9 @@ fn functions_in(lines: &[&str], indent: &str) -> Vec<PortFn> {
}
let js_name = doc_name(&lines[..i], "Port of `")
.map(|n| n.rsplit('.').next().unwrap_or(&n).to_string());
+ let named = js_name.is_some();
if let Some(f) = parse_signature(&signature, is_async, js_name) {
- out.push(f);
+ out.push((f, named));
}
i = j + 1;
}
diff --git a/src/main.rs b/src/main.rs
index 4cf96dda..db06287e 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -1578,6 +1578,15 @@ fn run() -> Result<ExitCode> {
r.files.join(", "),
r.functions.join(", ")
);
+ if !r.not_exports.is_empty() {
+ let unit = bridge::Manifest::load(&crate_dir)?.unit;
+ for name in &r.not_exports {
+ say!(
+ "`{name}` is not an export of `{unit}` and is now part of the bridged API; \
+ make it private (`fn`) if it is a helper"
+ );
+ }
+ }
}
Cmd::Build {
crate_dir,
diff --git a/tests/loop.rs b/tests/loop.rs
index f9bb8d3b..57b33c26 100644
--- a/tests/loop.rs
+++ b/tests/loop.rs
@@ -74,6 +74,174 @@ fn refresh_keeps_the_original_name_for_raw_rust_identifiers() {
std::fs::remove_dir_all(dir).unwrap();
}
+/// A crate for one source file, bridged in a scratch repository named `name`.
+fn bridged_file(name: &str, file: &str, source: &str) -> (common::Scratch, PathBuf) {
+ let root = common::Scratch::new(
+ std::env::temp_dir().join(format!("rust-anything-{name}-{}", std::process::id())),
+ );
+ std::fs::write(root.join(file), source).unwrap();
+ let dir = root.join("rust/mathx-rs");
+ bridge::bridge(&bridge::Options {
+ root: &root,
+ unit: file,
+ kind: None,
+ out: Some(dir.clone()),
+ name: None,
+ force: false,
+ keep: Vec::new(),
+ lang: None,
+ batch: Vec::new(),
+ as_json: Vec::new(),
+ allocator: Default::default(),
+ })
+ .unwrap();
+ (root, dir)
+}
+
+/// Adds a `pub fn` that matches no export of the original to the crate's `port.rs`.
+fn add_helper(dir: &Path) {
+ let port = dir.join("src/port.rs");
+ let source = std::fs::read_to_string(&port).unwrap();
+ std::fs::write(
+ &port,
+ source + "\npub fn helper_extra(x: i64) -> Result<i64, String> {\n Ok(x)\n}\n",
+ )
+ .unwrap();
+}
+
+/// The MCP `refresh` tool's result for a crate.
+fn refresh_tool(dir: &Path) -> serde_json::Value {
+ let response = rust_anything::mcp::handle(&serde_json::json!({
+ "jsonrpc": "2.0",
+ "id": 1,
+ "method": "tools/call",
+ "params": { "name": "refresh", "arguments": { "crate": dir } },
+ }))
+ .unwrap();
+ assert_ne!(response["result"]["isError"], true, "{response}");
+ response["result"]["structuredContent"].clone()
+}
+
+#[test]
+fn refresh_keeps_the_rust_name_of_a_python_function_that_is_not_an_export_and_says_so() {
+ let (_root, dir) = bridged_file(
+ "not-an-export-py",
+ "mathx.py",
+ "def scale(x: float, k: float) -> float:\n return x * k\n",
+ );
+ add_helper(&dir);
+
+ let out = common::cli().arg("refresh").arg(&dir).output().unwrap();
+ let stdout = String::from_utf8_lossy(&out.stdout);
+ assert!(out.status.success(), "{out:?}");
+ assert!(stdout.contains(" for scale, helper_extra\n"), "{stdout}");
+ assert!(
+ stdout.contains(
+ "`helper_extra` is not an export of `mathx.py` and is now part of the bridged API; \
+ make it private (`fn`) if it is a helper\n"
+ ),
+ "{stdout}"
+ );
+ let init = std::fs::read_to_string(dir.join("python/mathx_rs/__init__.py")).unwrap();
+ assert!(
+ init.contains("helper_extra = _native.helper_extra\n"),
+ "{init}"
+ );
+ assert!(!init.contains("helperExtra"), "{init}");
+ let refreshed = refresh_tool(&dir);
+ assert_eq!(
+ refreshed["not_exports"],
+ serde_json::json!(["helper_extra"]),
+ "{refreshed}"
+ );
+}
+
+#[test]
+fn refresh_keeps_the_doc_name_of_a_python_function_that_is_not_an_export() {
+ let (_root, dir) = bridged_file(
+ "doc-named-py",
+ "mathx.py",
+ "def scale(x: float, k: float) -> float:\n return x * k\n",
+ );
+ let port = dir.join("src/port.rs");
+ let source = std::fs::read_to_string(&port).unwrap();
+ std::fs::write(
+ &port,
+ source
+ + "\n/// Port of `rescale`\npub fn rescale_it(x: i64) -> Result<i64, String> {\n Ok(x)\n}\n\
+ \n/// Port of `widenIt`\npub fn widen_it(x: i64) -> Result<i64, String> {\n Ok(x)\n}\n",
+ )
+ .unwrap();
+ let refreshed = refresh_tool(&dir);
+ assert_eq!(
+ refreshed["functions"],
+ serde_json::json!(["scale", "rescale", "widenIt"])
+ );
+ assert_eq!(
+ refreshed["not_exports"],
+ serde_json::json!(["rescale_it", "widen_it"])
+ );
+}
+
+#[test]
+fn refresh_does_not_let_a_python_helper_replace_a_name_the_loader_uses() {
+ let (_root, dir) = bridged_file(
+ "underscore-py",
+ "mathx.py",
+ "def scale(x: float, k: float) -> float:\n return x * k\n",
+ );
+ let port = dir.join("src/port.rs");
+ let source = std::fs::read_to_string(&port).unwrap();
+ std::fs::write(
+ &port,
+ source
+ + "\npub fn _native(x: i64) -> Result<i64, String> {\n Ok(x)\n}\n\
+ \npub fn helper_extra(x: i64) -> Result<i64, String> {\n Ok(x)\n}\n",
+ )
+ .unwrap();
+ assert_eq!(
+ refresh_tool(&dir)["functions"],
+ serde_json::json!(["scale", "Native", "helper_extra"])
+ );
+}
+
+#[test]
+fn refresh_names_a_function_that_is_not_an_export_in_snake_case_for_ruby_and_camel_case_for_ts() {
+ let (_root, dir) = bridged_file(
+ "not-an-export-rb",
+ "mathx.rb",
+ "module Mathx\n # @param x [Integer]\n # @return [Integer]\n def self.scale(x)\n x * 2\n end\nend\n",
+ );
+ add_helper(&dir);
+ let refreshed = refresh_tool(&dir);
+ assert_eq!(
+ refreshed["functions"],
+ serde_json::json!(["scale", "helper_extra"])
+ );
+ assert_eq!(
+ refreshed["not_exports"],
+ serde_json::json!(["helper_extra"])
+ );
+ let lib = std::fs::read_to_string(dir.join("src/lib.rs")).unwrap();
+ assert!(
+ lib.contains(r#"define_module_function("helper_extra", "#),
+ "{lib}"
+ );
+
+ let dir = bridged("not-an-export-ts");
+ add_helper(&dir);
+ let refreshed = refresh_tool(&dir);
+ std::fs::remove_dir_all(&dir).unwrap();
+ assert_eq!(
+ refreshed["functions"],
+ serde_json::json!(["rangeOf", "words", "count", "helperExtra"])
+ );
+ assert_eq!(
+ refreshed["not_exports"],
+ serde_json::json!(["helper_extra"])
+ );
+}
+
#[test]
fn bridge_writes_a_crate_and_never_overwrites_it() {
let dir = bridged("bridge");