Skip to main content

rust_anything/
codegen_ruby.rs

1//! Ruby: the Fiddle wrapper (the original module functions over the Rust library), and the
2//! driver that calls them by name for record, diff and bench.
3
4use std::fmt::Write as _;
5
6use crate::bridge::Manifest;
7use crate::lang::ruby::{receiver, signature};
8
9/// JSON markers shared by the wrapper and the driver: floats JSON cannot carry, symbols,
10/// hashes with non-string keys, and other objects.
11const CODEC_RB: &str = r#"
12module RustAnythingCodec
13  module_function
14
15  def enc(v)
16    case v
17    when Float
18      return { "$num" => "NaN" } if v.nan?
19      return { "$num" => v.positive? ? "Infinity" : "-Infinity" } if v.infinite?
20      return { "$num" => "-0" } if v.zero? && (1.0 / v).negative?
21
22      v
23    when Integer, String, true, false, nil then v
24    when Symbol then { "$sym" => v.to_s }
25    when Array then v.map { |x| enc(x) }
26    when Hash
27      if v.keys.all? { |k| k.is_a?(String) }
28        v.transform_values { |x| enc(x) }
29      else
30        { "$hash" => v.map { |k, x| [enc(k), enc(x)] } }
31      end
32    else
33      { "$object" => v.class.name, "value" => v.respond_to?(:to_h) ? enc(v.to_h) : v.inspect }
34    end
35  end
36
37  def dec(v)
38    case v
39    when Array then v.map { |x| dec(x) }
40    when Hash
41      if v.size == 1 && v.key?("$num")
42        { "NaN" => Float::NAN, "Infinity" => Float::INFINITY, "-Infinity" => -Float::INFINITY, "-0" => -0.0 }.fetch(v["$num"])
43      elsif v.size == 1 && v.key?("$undefined")
44        nil
45      elsif v.size == 1 && v.key?("$sym")
46        v["$sym"].to_sym
47      elsif v.size == 1 && v.key?("$hash")
48        v["$hash"].to_h { |k, x| [dec(k), dec(x)] }
49      else
50        v.transform_values { |x| dec(x) }
51      end
52    else v
53    end
54  end
55end
56"#;
57
58/// The wrapper: the same modules and module functions, each calling the Rust library.
59pub fn wrapper(m: &Manifest, api: &crate::codegen::PortApi) -> Result<String, String> {
60    let lib = m.lib_name();
61    let mut out = native(m);
62    out.push_str(&module_functions(m, &lib));
63    out.push_str(&crate::codegen_batch_native::ruby_wrapper(m, api)?);
64    Ok(out)
65}
66
67/// The codec and the module that calls the Rust library.
68fn native(m: &Manifest) -> String {
69    let lib = m.lib_name();
70    format!(
71        "# frozen_string_literal: true\n\n\
72         # The Rust port of `{unit}`, generated by rust-anything: the same module functions, each\n\
73         # calling the Rust extension `{lib}_native`. Load it in place of the original files.\n\
74         # Regenerate with `rust-anything refresh`.\n\n\
75         require_relative \"{lib}_native\"\n",
76        unit = m.unit,
77    )
78}
79
80fn module_functions(m: &Manifest, lib: &str) -> String {
81    let mut out = String::new();
82    let mut by_module: Vec<(String, Vec<String>)> = Vec::new();
83    for f in &m.exports {
84        let (recv, name) = receiver(f);
85        let sig = signature(f);
86        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
87        let def = format!(
88            "def self.{name}({sig})\n  RustAnythingNative{}.{}({})\nend",
89            camel(lib),
90            f.name,
91            args.join(", ")
92        );
93        match by_module.iter_mut().find(|(r, _)| *r == recv) {
94            Some((_, defs)) => defs.push(def),
95            None => by_module.push((recv, vec![def])),
96        }
97    }
98    for (recv, defs) in by_module {
99        let parts: Vec<&str> = recv.split("::").collect();
100        let mut code = String::new();
101        for (depth, part) in parts.iter().enumerate() {
102            let _ = writeln!(code, "{}module {part}", "  ".repeat(depth));
103        }
104        let indent = "  ".repeat(parts.len());
105        for (i, def) in defs.iter().enumerate() {
106            if i > 0 {
107                code.push('\n');
108            }
109            for line in def.lines() {
110                let _ = writeln!(code, "{indent}{line}");
111            }
112        }
113        for depth in (0..parts.len()).rev() {
114            let _ = writeln!(code, "{}end", "  ".repeat(depth));
115        }
116        let _ = write!(out, "\n{code}");
117    }
118    out
119}
120
121/// A shadow file: require it after the original. Each module function runs the original and
122/// the Rust port, returns the original's result and counts mismatches. `RUST_ANYTHING_MODE=old`
123/// runs the original only, `new` the port only.
124pub fn shadow(m: &Manifest) -> String {
125    let lib = m.lib_name();
126    let call = format!("RustAnythingNative{}", camel(&lib));
127    let mut out = format!(
128        "# frozen_string_literal: true\n\n\
129         # Runs `{unit}` and its Rust port side by side. Generated by rust-anything: require it after the\n\
130         # original files. RUST_ANYTHING_MODE=old|shadow|new.\n\n\
131         require \"json\"\nrequire_relative \"{lib}_native\"\n{CODEC_RB}",
132        unit = m.unit,
133    );
134    out.push_str(
135        r#"
136module RustAnythingShadow
137  MODE = ENV.fetch("RUST_ANYTHING_MODE", "shadow")
138  @calls = 0
139  @mismatches = 0
140
141  class << self
142    attr_reader :calls, :mismatches
143
144    def compare(name, expected, actual)
145      @calls += 1
146      return if JSON.generate(RustAnythingCodec.enc(expected)) == JSON.generate(RustAnythingCodec.enc(actual))
147
148      @mismatches += 1
149      warn "[rust-anything] mismatch in #{name}: expected #{expected.inspect}, got #{actual.inspect}" if @mismatches <= 10
150    end
151  end
152end
153"#,
154    );
155    for f in &m.exports {
156        let (recv, name) = receiver(f);
157        let sig = signature(f);
158        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
159        let args = args.join(", ");
160        let _ = write!(
161            out,
162            "
163{recv}.singleton_class.prepend(Module.new do
164               def {name}({sig})
165                 return {call}.{fname}({args}) if RustAnythingShadow::MODE == \"new\"
166
167                 expected = super
168                 unless RustAnythingShadow::MODE == \"old\"
169                   actual = begin
170        {call}.{fname}({args})
171                   rescue StandardError => e
172        e
173      end
174                   RustAnythingShadow.compare(\"{recv}.{name}\", expected, actual)
175    end
176                 expected
177  end
178end)
179",
180            fname = f.name,
181        );
182    }
183    out
184}
185
186pub fn camel(lib: &str) -> String {
187    lib.split('_')
188        .map(|p| {
189            let mut c = p.chars();
190            c.next()
191                .map(|f| f.to_uppercase().chain(c).collect::<String>())
192                .unwrap_or_default()
193        })
194        .collect()
195}
196
197/// `{ name: [receiver, method] }` for the driver.
198pub fn targets(m: &Manifest) -> serde_json::Value {
199    serde_json::Value::Object(
200        m.exports
201            .iter()
202            .map(|f| {
203                let (recv, name) = receiver(f);
204                (f.name.clone(), serde_json::json!([recv, name]))
205            })
206            .collect(),
207    )
208}
209
210pub fn driver() -> String {
211    format!("{CODEC_RB}\n{DRIVER_RB}")
212}
213
214const DRIVER_RB: &str = r#"
215require "json"
216
217mode, targets_path, cases_path, out_path, min_ms, *files = ARGV
218files.each { |f| require f }
219TARGETS = JSON.parse(File.read(targets_path))
220
221def call(c)
222  recv, name = TARGETS.fetch(c["fn"])
223  args = (c["args"] || []).dup
224  args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
225  args = RustAnythingCodec.dec(args)
226  kwargs = RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)
227  value = Object.const_get(recv).public_send(name, *args, **kwargs)
228  { "ok" => RustAnythingCodec.enc(value) }
229rescue StandardError, ScriptError => e
230  { "error" => e.message, "error_type" => e.class.name }
231end
232
233def lines(path)
234  File.readlines(path, chomp: true).reject(&:empty?).map { |l| JSON.parse(l) }
235end
236
237def same?(expected, got)
238  return got.key?("error") && expected["error_type"] == got["error_type"] if expected.key?("error")
239
240  !got.key?("error") && JSON.generate(expected["ok"]) == JSON.generate(got["ok"])
241end
242
243case mode
244when "record"
245  File.open(out_path, "w") do |out|
246    JSON.parse(File.read(cases_path)).each do |c|
247      line = { "fn" => c["fn"], "args" => c["args"] }
248      line["kwargs"] = c["kwargs"] if c["kwargs"]
249      line.merge!(call(c))
250      begin
251        out.puts(JSON.generate(line))
252      rescue JSON::GeneratorError, Encoding::UndefinedConversionError
253        next
254      end
255    end
256  end
257when "diff"
258  summary = { "total" => 0, "passed" => 0, "failed" => 0, "missing" => [], "mismatches" => [] }
259  lines(cases_path).each do |c|
260    summary["total"] += 1
261    got = call(c)
262    expected = c.slice("ok", "error", "error_type")
263    if same?(expected, got)
264      summary["passed"] += 1
265    else
266      summary["failed"] += 1
267      shown = c["kwargs"].nil? || c["kwargs"].empty? ? c["args"] : c["args"] + [c["kwargs"]]
268      summary["mismatches"] << { "fn" => c["fn"], "args" => shown, "expected" => expected, "actual" => got }
269    end
270  end
271  File.write(out_path, JSON.generate(summary))
272when "bench"
273  groups = lines(cases_path).group_by { |c| c["fn"] }
274  result = {}
275  groups.each do |name, cases|
276    # Arguments are decoded once, the method looked up once: only the calls are timed.
277    recv, meth = TARGETS.fetch(name)
278    target = Object.const_get(recv).method(meth)
279    prepared = cases.map do |c|
280      args = (c["args"] || []).dup
281      args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
282      [RustAnythingCodec.dec(args), RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)]
283    end
284    once = lambda do
285      prepared.each do |args, kwargs|
286        target.call(*args, **kwargs)
287      rescue StandardError
288        nil
289      end
290    end
291    once.call
292    passes = 0
293    start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
294    loop do
295      once.call
296      passes += 1
297      elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
298      if elapsed * 1000 >= min_ms.to_i
299        result[name] = { "cases" => cases.size, "ns" => elapsed * 1e9 / (passes * cases.size) }
300        break
301      end
302    end
303  end
304  File.write(out_path, JSON.generate(result))
305end
306"#;
307
308/// Whether a port type holds `serde_json::Value`: such values convert through `rbconv.rs`;
309/// everything else (strings, numbers, booleans, `Vec`, `Option`, `HashMap`) converts directly.
310fn via_json(ty: &str) -> bool {
311    ty.contains("Value")
312}
313
314/// `src/lib.rs` of a Ruby crate: a magnus extension defining `RustAnythingNative<Lib>` with one
315/// module function per port function, positional arguments only (the Ruby wrapper keeps the
316/// original defaults and keywords).
317pub fn lib_rs(m: &Manifest, api: &crate::codegen::PortApi) -> Result<String, String> {
318    let lib = m.lib_name();
319    let mut out = format!(
320        "//! Ruby extension for `{unit}`, generated by rust-anything from `src/port.rs`. Regenerate with\n\
321         //! `rust-anything refresh`. Values convert directly between Ruby and Rust: no JSON.\n\n\
322         use magnus::{{Error, ExceptionClass, Module, Object, Ruby, function, method}};\n\
323         #[allow(unused_imports)]\nuse serde_json::Value;\n\n\
324         pub mod port;\nmod rbconv;\n\n\
325         /// `Err(\"ArgumentError: message\")` raises that exception class; otherwise a RuntimeError.\n\
326         fn error(ruby: &Ruby, message: String) -> Error {{\n    \
327         if let Some((kind, text)) = message.split_once(\": \")\n        \
328         && kind.starts_with(|c: char| c.is_ascii_uppercase())\n        \
329         && kind.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')\n        \
330         && let Ok(class) = ruby.class_object().const_get::<_, ExceptionClass>(kind)\n    {{\n        \
331         return Error::new(class, text.to_string());\n    }}\n    \
332         Error::new(ruby.exception_runtime_error(), message)\n}}\n\n\
333         /// Runs the port; a panic becomes a RuntimeError instead of Ruby's uncatchable `fatal`.\n\
334         fn guard<T>(ruby: &Ruby, f: impl FnOnce() -> Result<T, String>) -> Result<T, Error> {{\n    \
335         match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {{\n        \
336         Ok(result) => result.map_err(|m| error(ruby, m)),\n        \
337         Err(panic) => {{\n            \
338         let text = panic\n                .downcast_ref::<&str>()\n                .map(ToString::to_string)\n                \
339         .or_else(|| panic.downcast_ref::<String>().cloned())\n                .unwrap_or_default();\n            \
340         Err(Error::new(ruby.exception_runtime_error(), format!(\"Rust panic: {{text}}\")))\n        }}\n    }}\n}}\n",
341        unit = m.unit,
342    );
343    let mut defs = Vec::new();
344    for f in &api.functions {
345        let params: Vec<String> = f
346            .params
347            .iter()
348            .map(|(n, t)| {
349                if via_json(t) {
350                    format!("{n}: magnus::Value")
351                } else {
352                    format!("{n}: {t}")
353                }
354            })
355            .collect();
356        let mut body = String::new();
357        for (n, t) in f.params.iter().filter(|(_, t)| via_json(t)) {
358            let _ = writeln!(
359                body,
360                "    let {n}: {t} = rbconv::arg({n}).map_err(|m| error(ruby, m))?;"
361            );
362        }
363        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
364        let call = format!("port::{}({})", f.rust_name, args.join(", "));
365        let call = if f.fallible {
366            call
367        } else {
368            format!("Ok({call})")
369        };
370        let (ret, tail) = if f.ret == "()" {
371            ("()".to_string(), "")
372        } else if via_json(&f.ret) {
373            (
374                "magnus::Value".to_string(),
375                "\n        .and_then(|out| rbconv::to_rb(ruby, &out))",
376            )
377        } else {
378            (f.ret.clone(), "")
379        };
380        let rb_name = format!("rb_{}", f.rust_name.trim_start_matches("r#"));
381        let ruby_param = if params.is_empty() {
382            "ruby: &Ruby".to_string()
383        } else {
384            format!("ruby: &Ruby, {}", params.join(", "))
385        };
386        let _ = writeln!(
387            out,
388            "\n/// `{js}`.\nfn {rb_name}({ruby_param}) -> Result<{ret}, Error> {{\n{body}    guard(ruby, || {call}){tail}\n}}",
389            js = f.js_name,
390        );
391        defs.push(format!(
392            "    native.define_module_function(\"{}\", function!({rb_name}, {}))?;",
393            f.js_name,
394            f.params.len()
395        ));
396    }
397    let (batches, batch_init) = crate::codegen_batch_native::ruby_rs(m, api)?;
398    out.push_str(&batches);
399    let _ = writeln!(
400        out,
401        "\n#[magnus::init(name = \"{lib}_native\")]\nfn init(ruby: &Ruby) -> Result<(), Error> {{\n    \
402         let native = ruby.define_module(\"RustAnythingNative{camel}\")?;\n{}\n{batch_init}    Ok(())\n}}",
403        defs.join("\n"),
404        camel = camel(&lib),
405    );
406    Ok(out)
407}
408
409pub fn cargo_toml(m: &Manifest) -> String {
410    format!(
411        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
412         description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
413         [lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\nmagnus = \"0.8\"\n\
414         serde = {{ version = \"1\", features = [\"derive\"] }}\n\
415         serde_json = {{ version = \"1\", features = [\"preserve_order\", \"float_roundtrip\"] }}\n\n\
416         [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n",
417        m.crate_name, m.unit
418    )
419}
420
421pub const BUILD_RS: &str = r#"fn main() {
422    if std::env::var("CARGO_CFG_TARGET_OS").as_deref() == Ok("macos") {
423        println!("cargo:rustc-cdylib-link-arg=-Wl,-undefined,dynamic_lookup");
424    }
425}
426"#;
427
428/// `src/rbconv.rs`: Ruby values to `serde_json::Value` and back, with the markers recorded
429/// cases use (`$num`, `$sym`, `$hash`, `$int`).
430pub const RBCONV_RS: &str = r#"//! Ruby values to `serde_json::Value` and back, in Rust. Generated by rust-anything.
431
432// Ports without dynamic values use only some of these.
433#![allow(dead_code)]
434
435use magnus::{Float, Integer, RArray, RHash, RString, Ruby, Symbol, value::ReprValue};
436use serde_json::{Map, Value, json};
437
438/// A Ruby value as JSON.
439pub fn from_rb(v: magnus::Value) -> Result<Value, String> {
440    let ruby = Ruby::get().map_err(|e| e.to_string())?;
441    if v.is_nil() {
442        return Ok(Value::Null);
443    }
444    if v.is_kind_of(ruby.class_true_class()) {
445        return Ok(Value::Bool(true));
446    }
447    if v.is_kind_of(ruby.class_false_class()) {
448        return Ok(Value::Bool(false));
449    }
450    if let Some(i) = Integer::from_value(v) {
451        return Ok(match i.to_i64() {
452            Ok(n) => json!(n),
453            Err(_) => json!({"$int": v.funcall::<_, _, String>("to_s", ()).map_err(|e| e.to_string())?}),
454        });
455    }
456    if let Some(f) = Float::from_value(v) {
457        let x = f.to_f64();
458        return Ok(if x.is_nan() {
459            json!({"$num": "NaN"})
460        } else if x.is_infinite() {
461            json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
462        } else if x == 0.0 && x.is_sign_negative() {
463            json!({"$num": "-0"})
464        } else {
465            json!(x)
466        });
467    }
468    if let Some(s) = RString::from_value(v) {
469        return s.to_string().map(Value::String).map_err(|e| e.to_string());
470    }
471    if let Some(s) = Symbol::from_value(v) {
472        return Ok(json!({"$sym": s.name().map_err(|e| e.to_string())?}));
473    }
474    if let Some(a) = RArray::from_value(v) {
475        let mut out = Vec::with_capacity(a.len());
476        for item in a.into_iter() {
477            out.push(from_rb(item)?);
478        }
479        return Ok(Value::Array(out));
480    }
481    if let Some(h) = RHash::from_value(v) {
482        let mut map = Map::new();
483        let mut pairs = Vec::new();
484        let mut string_keys = true;
485        h.foreach(|k: magnus::Value, x: magnus::Value| {
486            let value = from_rb(x).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
487            match RString::from_value(k) {
488                Some(s) => {
489                    let key = s.to_string()?;
490                    pairs.push(json!([key.clone(), value.clone()]));
491                    map.insert(key, value);
492                }
493                None => {
494                    string_keys = false;
495                    let key = from_rb(k).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
496                    pairs.push(json!([key, value]));
497                }
498            }
499            Ok(magnus::r_hash::ForEach::Continue)
500        })
501        .map_err(|e| e.to_string())?;
502        return Ok(if string_keys { Value::Object(map) } else { json!({"$hash": pairs}) });
503    }
504    Err(format!("TypeError: unsupported argument {}", v.class().inspect()))
505}
506
507/// A Ruby argument as the port's parameter type.
508pub fn arg<T: serde::de::DeserializeOwned>(v: magnus::Value) -> Result<T, String> {
509    serde_json::from_value(from_rb(v)?).map_err(|e| format!("TypeError: {e}"))
510}
511
512/// A port result as a Ruby value.
513pub fn to_rb<T: serde::Serialize>(ruby: &Ruby, out: &T) -> Result<magnus::Value, magnus::Error> {
514    let value = serde_json::to_value(out).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e.to_string()))?;
515    value_to_rb(ruby, &value)
516}
517
518fn value_to_rb(ruby: &Ruby, v: &Value) -> Result<magnus::Value, magnus::Error> {
519    Ok(match v {
520        Value::Null => ruby.qnil().as_value(),
521        Value::Bool(true) => ruby.qtrue().as_value(),
522        Value::Bool(false) => ruby.qfalse().as_value(),
523        Value::Number(n) => match n.as_i64() {
524            Some(i) if !n.is_f64() => ruby.integer_from_i64(i).as_value(),
525            _ => ruby.float_from_f64(n.as_f64().unwrap_or(f64::NAN)).as_value(),
526        },
527        Value::String(s) => ruby.str_new(s).as_value(),
528        Value::Array(items) => {
529            let array = ruby.ary_new_capa(items.len());
530            for item in items {
531                array.push(value_to_rb(ruby, item)?)?;
532            }
533            array.as_value()
534        }
535        Value::Object(o) if o.len() == 1 && o.keys().next().is_some_and(|k| k.starts_with('$')) => {
536            let (key, inner) = o.iter().next().expect("one entry");
537            match key.as_str() {
538                "$num" => ruby
539                    .float_from_f64(match inner.as_str() {
540                        Some("Infinity") => f64::INFINITY,
541                        Some("-Infinity") => f64::NEG_INFINITY,
542                        Some("-0") => -0.0,
543                        _ => f64::NAN,
544                    })
545                    .as_value(),
546                "$sym" => ruby.to_symbol(inner.as_str().unwrap_or_default()).as_value(),
547                "$int" => ruby.str_new(inner.as_str().unwrap_or("0")).funcall("to_i", ())?,
548                "$hash" => {
549                    let hash = ruby.hash_new();
550                    for pair in inner.as_array().map(Vec::as_slice).unwrap_or_default() {
551                        if let Some([k, x]) = pair.as_array().map(Vec::as_slice) {
552                            hash.aset(value_to_rb(ruby, k)?, value_to_rb(ruby, x)?)?;
553                        }
554                    }
555                    hash.as_value()
556                }
557                _ => {
558                    let hash = ruby.hash_new();
559                    hash.aset(ruby.str_new(key), value_to_rb(ruby, inner)?)?;
560                    hash.as_value()
561                }
562            }
563        }
564        Value::Object(o) => {
565            let hash = ruby.hash_new();
566            for (k, x) in o {
567                hash.aset(ruby.str_new(k), value_to_rb(ruby, x)?)?;
568            }
569            hash.as_value()
570        }
571    })
572}
573"#;