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