Skip to content

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.

ruby: port methods that take *rest or keyword arguments

Mohit Mishra525618ffddc4
diff --git a/src/cfamily.rs b/src/cfamily.rs
index be57fb7..a68761d 100644
--- a/src/cfamily.rs
+++ b/src/cfamily.rs
@@ -382,7 +382,7 @@ fn parse_params(list: &str) -> Vec<Param> {
let (ty, name) = (decl[..name_start].trim(), &decl[name_start..]);
let (ty, name) = if ty.is_empty() || ty.ends_with("::") { (decl, "") } else { (ty, name) };
let ty = if array { format!("{}*", ty.trim()) } else { ty.to_string() };
- Param { name: name.to_string(), annotation: Some(squash(&ty)), default, kwonly: false }
+ Param { name: name.to_string(), annotation: Some(squash(&ty)), default, kwonly: false, splat: false }
})
.collect()
}
diff --git a/src/hotspot.rs b/src/hotspot.rs
index 1d3615f..97cf24c 100644
--- a/src/hotspot.rs
+++ b/src/hotspot.rs
@@ -12,8 +12,10 @@ pub struct Param {
pub annotation: Option<String>,
/// Default value as source text, e.g. "2" or "None".
pub default: Option<String>,
- /// Keyword-only (after `*` in Python).
+ /// Keyword-only (after `*` in Python; Ruby's keyword arguments).
pub kwonly: bool,
+ /// Takes the remaining positional arguments, as one array (Ruby's `*rest`).
+ pub splat: bool,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
diff --git a/src/kotlin.rs b/src/kotlin.rs
index 63c36db..c14a11a 100644
--- a/src/kotlin.rs
+++ b/src/kotlin.rs
@@ -476,7 +476,7 @@ fn describe_file(path: &Path) -> Vec<Method> {
name: "receiver".into(),
annotation: Some(r.clone()),
default: None,
- kwonly: false,
+ ..Param::default()
});
}
for p in split_top(&f.params) {
@@ -491,7 +491,7 @@ fn describe_file(path: &Path) -> Vec<Method> {
let name = words(name).last().copied().unwrap_or_default().to_string();
// inside the function a vararg is an array (IntArray, Array<String>...), passed with *
let ty = if vararg { format!("vararg {}", vararg_array(ty.trim())) } else { ty.trim().to_string() };
- params.push(Param { name, annotation: Some(ty), default, kwonly: false });
+ params.push(Param { name, annotation: Some(ty), default, ..Param::default() });
}
let body = f.body.map(|(b, e)| &code[b..=e]).unwrap_or_default();
let io: Vec<&str> = IO.iter().filter(|w| body.contains(*w)).map(|w| w.trim_end_matches('(')).collect();
diff --git a/src/python.rs b/src/python.rs
index f26a4bd..4634669 100644
--- a/src/python.rs
+++ b/src/python.rs
@@ -1189,6 +1189,7 @@ sys.exit(1 if fails else 0)
annotation: Some(annotation.into()),
default: default.map(Into::into),
kwonly,
+ splat: false,
};
let mut hs = Hotspot {
name: "join_words".into(),
diff --git a/src/ruby.rs b/src/ruby.rs
index 64cab3d..b627af5 100644
--- a/src/ruby.rs
+++ b/src/ruby.rs
@@ -3,7 +3,7 @@
//! The same bridge works for any language that can call C.
use crate::backend::{self, Profile, Recording};
-use crate::hotspot::Hotspot;
+use crate::hotspot::{Hotspot, Param};
use crate::native::{cargo_toml, snake};
use crate::python::DISABLE_ENV;
use crate::state::{Ctx, Port, Verify};
@@ -72,6 +72,26 @@ fn owner(hs_owner: Option<&str>) -> &str {
hs_owner.unwrap_or("Object")
}
+/// Ruby source for a lambda that takes the method's parameters (`a, b = 2, *xs, scale: 1`) and
+/// returns their values in order (`[a, b, xs, scale]`): run with instance_exec, it binds a call's
+/// arguments the way the method does. Made in the method's module, so defaults see its constants.
+fn binder(hs_owner: Option<&str>, params: &[Param]) -> String {
+ let list: Vec<String> = params
+ .iter()
+ .map(|p| match (&p.default, p.kwonly, p.splat) {
+ (_, _, true) => format!("*{}", p.name),
+ (Some(d), true, _) => format!("{}: {d}", p.name),
+ (None, true, _) => format!("{}:", p.name),
+ (Some(d), false, _) => format!("{} = {d}", p.name),
+ (None, false, _) => p.name.clone(),
+ })
+ .collect();
+ let names: Vec<&str> = params.iter().map(|p| p.name.as_str()).collect();
+ let code = format!("->({}) {{ [{}] }}", list.join(", "), names.join(", "));
+ let base = owner(hs_owner).trim_end_matches(".singleton_class");
+ format!("{base}.class_eval('{}')", code.replace('\\', "\\\\").replace('\'', "\\'"))
+}
+
/// Wrap the method for one run: a line appended to its file (or put before the entry script's
/// "if __FILE__ == $0" block) hands it to the preloaded recorder. The file is restored afterwards.
pub fn record(ctx: &Ctx, ruby: &str, args: &[String], hs: &Hotspot, out: &Path, limit: usize) -> Result<Recording> {
@@ -81,7 +101,12 @@ pub fn record(ctx: &Ctx, ruby: &str, args: &[String], hs: &Hotspot, out: &Path,
fs::create_dir_all(&backup_dir)?;
let backup = backup_dir.join(slug(&hs.file));
fs::write(&backup, &original)?;
- let line = format!("$__fast_anything_wrap&.call({}, :{})", owner(hs.owner.as_deref()), hs.name);
+ let line = format!(
+ "$__fast_anything_wrap&.call({}, :{}, {})",
+ owner(hs.owner.as_deref()),
+ hs.name,
+ binder(hs.owner.as_deref(), &hs.params)
+ );
let id = format!("recording {}", hs.id);
let patched = if hs.module.as_deref() == Some("__main__") {
backend::insert_marked(&original, "#", &id, &line, main_guard)
@@ -246,7 +271,7 @@ pub fn verify(ctx: &Ctx, port: &Port) -> Result<Verify> {
// ------------------------------------------------------------------ the shim
-pub fn shim(port: &Port, lib_rel: &str) -> String {
+pub fn shim(port: &Port, params: &[Param], lib_rel: &str) -> String {
let owner = owner(port.owner.as_deref());
let name = &port.func;
let mut lines = vec![
@@ -276,11 +301,13 @@ pub fn shim(port: &Port, lib_rel: &str) -> String {
" else v".to_string(),
" end".to_string(),
" end".to_string(),
- format!(" {owner}.send(:define_method, :{name}) do |*args|"),
+ format!(" bind = {}", binder(port.owner.as_deref(), params)),
+ format!(" {owner}.send(:define_method, :{name}) do |*args, **kw|"),
+ " values = instance_exec(*args, **kw, &bind)".to_string(),
" input = begin".to_string(),
- " JSON.generate(args)".to_string(),
+ " JSON.generate(values)".to_string(),
" rescue JSON::GeneratorError".to_string(),
- " JSON.generate(wire.(args))".to_string(),
+ " JSON.generate(wire.(values))".to_string(),
" end".to_string(),
" size = Fiddle::Pointer.malloc(Fiddle::SIZEOF_SIZE_T, Fiddle::RUBY_FREE)".to_string(),
" out = call.call(input, input.bytesize, size)".to_string(),
@@ -311,7 +338,13 @@ pub fn enable(ctx: &Ctx, port: &Port) -> Result<()> {
let from = file.parent().context("file has no folder")?;
let (_, lib) = backend::Lang::Ruby.artifact(&port.ext);
let rel = forward_slashes(&relative(from, &ctx.lib_dir().join(lib)));
- let block = shim(port, &rel);
+ let hs = ctx
+ .state
+ .hotspots
+ .iter()
+ .find(|h| h.id == port.id)
+ .with_context(|| format!("{} isn't in the last scan", port.id))?;
+ let block = shim(port, &hs.params, &rel);
let patched = if port.module == "__main__" {
backend::insert_marked(&text, "#", &port.id, &block, main_guard)
} else {
@@ -330,6 +363,77 @@ pub fn disable(ctx: &Ctx, port: &Port) -> Result<()> {
mod tests {
use super::*;
+ #[test]
+ fn splat_and_keyword_arguments_are_bound_like_the_method_binds_them() {
+ let Ok(ruby) = resolve("ruby", Path::new(".")) else {
+ eprintln!("no Ruby 3.3+ on PATH, skipping");
+ return;
+ };
+ let tmp = std::env::temp_dir();
+ // macOS's temp folder is behind a symlink; the profile has the real paths
+ let tmp = if cfg!(windows) { tmp } else { tmp.canonicalize().unwrap() };
+ let dir = tmp.join(format!("fa-rb-splat-test-{}", std::process::id()));
+ fs::create_dir_all(&dir).unwrap();
+ let lib = "module Score\n SCALE = 3\n\n def self.score(word, *weights, scale: SCALE, bonus: 0)\n total = 0\n 200.times { total += word.length * (weights.sum + bonus) * scale }\n total\n end\nend\n";
+ let app = "require_relative \"score\"\n\nt = 0\n2000.times { t += Score.score(\"ab\", 1, 2) + Score.score(\"c\", bonus: 1) + Score.score(\"d\", 4, scale: 2) }\nputs t\n";
+ fs::write(dir.join("score.rb"), lib).unwrap();
+ fs::write(dir.join("app.rb"), app).unwrap();
+ let ctx = Ctx::open(&dir).unwrap();
+ let run = || {
+ let p = profile(&ctx, &ruby, &["app.rb".into()])?;
+ let f = p.functions.iter().find(|f| f.name == "score").context("no score in the profile")?.clone();
+ let hs = Hotspot {
+ id: "score.Score.score".into(),
+ file: "score.rb".into(),
+ name: "score".into(),
+ module: Some("score".into()),
+ owner: f.owner.clone(),
+ params: f.params.clone(),
+ ..Hotspot::default()
+ };
+ let out = dir.join("cases.jsonl");
+ record(&ctx, &ruby, &["app.rb".into()], &hs, &out, 50)?;
+ let cases = fs::read_to_string(&out)?;
+ // the binder the shim uses, on its own
+ let bind = binder(hs.owner.as_deref(), &hs.params);
+ let script = format!(
+ "require \"json\"\nrequire_relative \"score\"\nbind = {bind}\nputs JSON.generate([Score.instance_exec(\"c\", bonus: 1, &bind), Score.instance_exec(\"d\", 4, 5, &bind)])\n"
+ );
+ fs::write(dir.join("bind.rb"), script)?;
+ let bound = output(Command::new(&ruby).arg("bind.rb").current_dir(&dir), "ruby")?;
+ anyhow::Ok((f, cases, bound))
+ };
+ let got = run();
+ let _ = fs::remove_dir_all(&dir);
+ let (f, cases, bound) = got.unwrap();
+ assert!(f.blockers.is_empty(), "{:?}", f.blockers);
+ let shape: Vec<_> =
+ f.params.iter().map(|p| (p.name.as_str(), p.default.as_deref(), p.kwonly, p.splat)).collect();
+ assert_eq!(
+ shape,
+ [
+ ("word", None, false, false),
+ ("weights", None, false, true),
+ ("scale", Some("SCALE"), true, false),
+ ("bonus", Some("0"), true, false)
+ ]
+ );
+ let args: std::collections::BTreeSet<String> =
+ cases.lines().map(|l| serde_json::from_str::<Value>(l).unwrap()["args"].to_string()).collect();
+ assert_eq!(
+ args.into_iter().collect::<Vec<_>>(),
+ [r#"["ab",[1,2],3,0]"#, r#"["c",[],3,1]"#, r#"["d",[4],2,0]"#],
+ "{cases}"
+ );
+ assert!(cases.lines().all(|l| !l.contains("raises")), "{cases}");
+ assert_eq!(
+ String::from_utf8_lossy(&bound.stdout).trim(),
+ r#"[["c",[],3,1],["d",[4,5],3,0]]"#,
+ "{}",
+ combined(&bound)
+ );
+ }
+
#[test]
fn ruby_defaults_become_json() {
assert_eq!(default_json("2").as_deref(), Some("2"));
diff --git a/src/ruby/recorder.rb b/src/ruby/recorder.rb
index 88b3957..c691c5b 100644
--- a/src/ruby/recorder.rb
+++ b/src/ruby/recorder.rb
@@ -74,6 +74,21 @@ module FastAnything
a.class == b.class && a == b
end
+
+ # Calls the method with the values of its parameters in order ([a, b, xs, scale] for
+ # a, b = 2, *xs, scale: 1): *rest spread out again, keywords by name.
+ def invoke(method, receiver, values, blk = nil)
+ positional = []
+ keywords = {}
+ method.parameters.reject { |kind, _| %i[keyrest block nokey].include?(kind) }.zip(values) do |(kind, name), value|
+ case kind
+ when :rest then positional.concat(value)
+ when :key, :keyreq then keywords[name] = value
+ else positional << value
+ end
+ end
+ method.bind_call(receiver, *positional, **keywords, &blk)
+ end
end
if ENV["FAST_ANYTHING_RECORD_OUT"]
@@ -109,7 +124,7 @@ if ENV["FAST_ANYTHING_RECORD_OUT"]
end
end
begin
- result = original.bind_call(receiver, *args, &blk)
+ result = invoke(original, receiver, args, blk)
rescue StandardError => e
if c
c["raises"] = e.class.name
@@ -141,10 +156,14 @@ if ENV["FAST_ANYTHING_RECORD_OUT"]
end
end
- $__fast_anything_wrap = lambda do |owner, name|
+ # bind: a lambda with the method's own parameters that returns their values, so arguments
+ # (defaults, *rest, keywords) are bound the way the method binds them
+ $__fast_anything_wrap = lambda do |owner, name, bind|
original = owner.instance_method(name)
was_private = owner.private_method_defined?(name)
- owner.send(:define_method, name) { |*args, &blk| FastAnything.record(original, self, args, blk) }
+ owner.send(:define_method, name) do |*args, **kw, &blk|
+ FastAnything.record(original, self, instance_exec(*args, **kw, &bind), blk)
+ end
owner.send(:private, name) if was_private
end
diff --git a/src/ruby/runner.rb b/src/ruby/runner.rb
index a375e7b..13a6a3a 100644
--- a/src/ruby/runner.rb
+++ b/src/ruby/runner.rb
@@ -105,9 +105,16 @@ def describe(path, line, name, entry, root)
params = []
if (ps = node.parameters)
- blockers << "takes keyword, block or splat arguments" if ps.keywords.any? || ps.keyword_rest || ps.block || ps.rest || ps.posts.any?
- ps.requireds.each { |r| params << { "name" => r.respond_to?(:name) ? r.name.to_s : r.slice, "annotation" => nil, "default" => nil } }
- ps.optionals.each { |o| params << { "name" => o.name.to_s, "annotation" => nil, "default" => o.value.slice } }
+ blockers << "takes a block, **options or ... arguments" if ps.keyword_rest || ps.block
+ blockers << "takes an unnamed * argument" if ps.rest && !(ps.rest.respond_to?(:name) && ps.rest.name)
+ blockers << "takes a destructured argument" if (ps.requireds + ps.posts).any? { |r| !r.respond_to?(:name) }
+ param = ->(name, default = nil, extra = {}) { { "name" => name.to_s, "annotation" => nil, "default" => default }.merge(extra) }
+ ps.requireds.each { |r| params << param.call(r.respond_to?(:name) ? r.name : r.slice) }
+ ps.optionals.each { |o| params << param.call(o.name, o.value.slice) }
+ # *rest is one array; keywords are passed by name
+ params << param.call(ps.rest.name, nil, "splat" => true) if ps.rest.respond_to?(:name) && ps.rest.name
+ ps.posts.each { |r| params << param.call(r.respond_to?(:name) ? r.name : r.slice) }
+ ps.keywords.each { |k| params << param.call(k.name, k.respond_to?(:value) ? k.value.slice : nil, "kwonly" => true) }
end
siblings = info[:defs].select { |x| x[:owner] == d[:owner] && x[:kind] != "nested" }.map { |x| x[:node].name }
@@ -395,7 +402,7 @@ def cmd_verify(job, _argv)
receiver = job["owner"] == "Object" ? Object.new : Object.const_get(job["owner"].delete_suffix(".singleton_class"))
owner = job["owner"] == "Object" ? Object : receiver.singleton_class
method = owner.instance_method(job["func"])
- original = ->(*args) { method.bind_call(receiver, *args) }
+ original = ->(*args) { FastAnything.invoke(method, receiver, args) }
cases = File.readlines(job["cases"], chomp: true).reject(&:empty?).map { |l| JSON.parse(l) }
recorded = cases.length