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 false if got["error"].to_s.start_with?("Rust panic:")
239  return got.key?("error") && expected["error_type"] == got["error_type"] if expected.key?("error")
240
241  !got.key?("error") && JSON.generate(expected["ok"]) == JSON.generate(got["ok"])
242end
243
244case mode
245when "record"
246  File.open(out_path, "w") do |out|
247    JSON.parse(File.read(cases_path)).each do |c|
248      line = { "fn" => c["fn"], "args" => c["args"] }
249      line["kwargs"] = c["kwargs"] if c["kwargs"]
250      line.merge!(call(c))
251      begin
252        out.puts(JSON.generate(line))
253      rescue JSON::GeneratorError, Encoding::UndefinedConversionError
254        next
255      end
256    end
257  end
258when "diff"
259  summary = { "total" => 0, "passed" => 0, "failed" => 0, "missing" => [], "mismatches" => [] }
260  lines(cases_path).each do |c|
261    summary["total"] += 1
262    got = call(c)
263    expected = c.slice("ok", "error", "error_type")
264    if same?(expected, got)
265      summary["passed"] += 1
266    else
267      summary["failed"] += 1
268      shown = c["kwargs"].nil? || c["kwargs"].empty? ? c["args"] : c["args"] + [c["kwargs"]]
269      summary["mismatches"] << { "fn" => c["fn"], "args" => shown, "expected" => expected, "actual" => got }
270    end
271  end
272  File.write(out_path, JSON.generate(summary))
273when "bench"
274  groups = lines(cases_path).group_by { |c| c["fn"] }
275  result = {}
276  groups.each do |name, cases|
277    # Arguments are decoded once, the method looked up once: only the calls are timed.
278    recv, meth = TARGETS.fetch(name)
279    target = Object.const_get(recv).method(meth)
280    prepared = cases.map do |c|
281      args = (c["args"] || []).dup
282      args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
283      [RustAnythingCodec.dec(args), RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)]
284    end
285    once = lambda do
286      prepared.each do |args, kwargs|
287        target.call(*args, **kwargs)
288      rescue StandardError
289        nil
290      end
291    end
292    once.call
293    passes = 0
294    start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
295    loop do
296      once.call
297      passes += 1
298      elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
299      if elapsed * 1000 >= min_ms.to_i
300        result[name] = { "cases" => cases.size, "ns" => elapsed * 1e9 / (passes * cases.size) }
301        break
302      end
303    end
304  end
305  File.write(out_path, JSON.generate(result))
306end
307"#;
308
309/// Whether a port type holds `serde_json::Value`: such values convert through `rbconv.rs`;
310/// everything else (strings, numbers, booleans, `Vec`, `Option`, `HashMap`) converts directly.
311fn via_json(ty: &str) -> bool {
312    ty.contains("Value")
313}
314
315/// `src/lib.rs` of a Ruby crate: a magnus extension defining `RustAnythingNative<Lib>` with one
316/// module function per port function, positional arguments only (the Ruby wrapper keeps the
317/// original defaults and keywords).
318pub fn lib_rs(m: &Manifest, api: &crate::codegen::PortApi) -> Result<String, String> {
319    let lib = m.lib_name();
320    let mut out = format!(
321        "//! Ruby extension for `{unit}`, generated by rust-anything from `src/port.rs`. Regenerate with\n\
322         //! `rust-anything refresh`. Values convert directly between Ruby and Rust: no JSON.\n\n\
323         use magnus::{{Error, ExceptionClass, Module, Object, Ruby, function, method}};\n\
324         #[allow(unused_imports)]\nuse serde_json::Value;\n\n\
325         pub mod port;\nmod rbconv;\n\n\
326         /// `Err(\"ArgumentError: message\")` raises that exception class; otherwise a RuntimeError.\n\
327         fn error(ruby: &Ruby, message: String) -> Error {{\n    \
328         if let Some((kind, text)) = message.split_once(\": \")\n        \
329         && kind.starts_with(|c: char| c.is_ascii_uppercase())\n        \
330         && kind.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')\n        \
331         && let Ok(class) = ruby.class_object().const_get::<_, ExceptionClass>(kind)\n    {{\n        \
332         return Error::new(class, text.to_string());\n    }}\n    \
333         Error::new(ruby.exception_runtime_error(), message)\n}}\n\n\
334         /// Runs the port; a panic becomes a RuntimeError instead of Ruby's uncatchable `fatal`.\n\
335         fn guard<T>(ruby: &Ruby, f: impl FnOnce() -> Result<T, String>) -> Result<T, Error> {{\n    \
336         match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {{\n        \
337         Ok(result) => result.map_err(|m| error(ruby, m)),\n        \
338         Err(panic) => {{\n            \
339         let text = panic\n                .downcast_ref::<&str>()\n                .map(ToString::to_string)\n                \
340         .or_else(|| panic.downcast_ref::<String>().cloned())\n                .unwrap_or_default();\n            \
341         Err(Error::new(ruby.exception_runtime_error(), format!(\"Rust panic: {{text}}\")))\n        }}\n    }}\n}}\n",
342        unit = m.unit,
343    );
344    let mut defs = Vec::new();
345    for f in &api.functions {
346        let params: Vec<String> = f
347            .params
348            .iter()
349            .map(|(n, t)| {
350                if via_json(t) {
351                    format!("{n}: magnus::Value")
352                } else {
353                    format!("{n}: {t}")
354                }
355            })
356            .collect();
357        let mut body = String::new();
358        for (n, t) in f.params.iter().filter(|(_, t)| via_json(t)) {
359            let _ = writeln!(
360                body,
361                "    let {n}: {t} = rbconv::arg({n}).map_err(|m| error(ruby, m))?;"
362            );
363        }
364        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
365        let call = format!("port::{}({})", f.rust_name, args.join(", "));
366        let call = if f.fallible {
367            call
368        } else {
369            format!("Ok({call})")
370        };
371        let (ret, tail) = if f.ret == "()" {
372            ("()".to_string(), "")
373        } else if via_json(&f.ret) {
374            (
375                "magnus::Value".to_string(),
376                "\n        .and_then(|out| rbconv::to_rb(ruby, &out))",
377            )
378        } else {
379            (f.ret.clone(), "")
380        };
381        let rb_name = format!("rb_{}", f.rust_name.trim_start_matches("r#"));
382        let ruby_param = if params.is_empty() {
383            "ruby: &Ruby".to_string()
384        } else {
385            format!("ruby: &Ruby, {}", params.join(", "))
386        };
387        let _ = writeln!(
388            out,
389            "\n/// `{js}`.\nfn {rb_name}({ruby_param}) -> Result<{ret}, Error> {{\n{body}    guard(ruby, || {call}){tail}\n}}",
390            js = f.js_name,
391        );
392        defs.push(format!(
393            "    native.define_module_function(\"{}\", function!({rb_name}, {}))?;",
394            f.js_name,
395            f.params.len()
396        ));
397    }
398    let (batches, batch_init) = crate::codegen_batch_native::ruby_rs(m, api)?;
399    out.push_str(&batches);
400    let _ = writeln!(
401        out,
402        "\n#[magnus::init(name = \"{lib}_native\")]\nfn init(ruby: &Ruby) -> Result<(), Error> {{\n    \
403         let native = ruby.define_module(\"RustAnythingNative{camel}\")?;\n{}\n{batch_init}    Ok(())\n}}",
404        defs.join("\n"),
405        camel = camel(&lib),
406    );
407    Ok(out)
408}
409
410pub fn cargo_toml(m: &Manifest) -> String {
411    format!(
412        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
413         description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
414         [lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\nmagnus = \"0.8\"\n\
415         serde = {{ version = \"1\", features = [\"derive\"] }}\n\
416         serde_json = {{ version = \"1\", features = [\"preserve_order\", \"float_roundtrip\"] }}\n\n\
417         [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n",
418        m.crate_name, m.unit
419    )
420}
421
422/// `src/rbconv.rs`: Ruby values to `serde_json::Value` and back, with the markers recorded
423/// cases use (`$num`, `$sym`, `$hash`, `$int`).
424pub const RBCONV_RS: &str = r#"//! Ruby values to `serde_json::Value` and back, in Rust. Generated by rust-anything.
425
426// Ports without dynamic values use only some of these.
427#![allow(dead_code)]
428
429use magnus::{Float, Integer, RArray, RHash, RString, Ruby, Symbol, value::ReprValue};
430use serde_json::{Map, Value, json};
431
432/// A Ruby value as JSON.
433pub fn from_rb(v: magnus::Value) -> Result<Value, String> {
434    let ruby = Ruby::get().map_err(|e| e.to_string())?;
435    if v.is_nil() {
436        return Ok(Value::Null);
437    }
438    if v.is_kind_of(ruby.class_true_class()) {
439        return Ok(Value::Bool(true));
440    }
441    if v.is_kind_of(ruby.class_false_class()) {
442        return Ok(Value::Bool(false));
443    }
444    if let Some(i) = Integer::from_value(v) {
445        return Ok(match i.to_i64() {
446            Ok(n) => json!(n),
447            Err(_) => json!({"$int": v.funcall::<_, _, String>("to_s", ()).map_err(|e| e.to_string())?}),
448        });
449    }
450    if let Some(f) = Float::from_value(v) {
451        let x = f.to_f64();
452        return Ok(if x.is_nan() {
453            json!({"$num": "NaN"})
454        } else if x.is_infinite() {
455            json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
456        } else if x == 0.0 && x.is_sign_negative() {
457            json!({"$num": "-0"})
458        } else {
459            json!(x)
460        });
461    }
462    if let Some(s) = RString::from_value(v) {
463        return s.to_string().map(Value::String).map_err(|e| e.to_string());
464    }
465    if let Some(s) = Symbol::from_value(v) {
466        return Ok(json!({"$sym": s.name().map_err(|e| e.to_string())?}));
467    }
468    if let Some(a) = RArray::from_value(v) {
469        let mut out = Vec::with_capacity(a.len());
470        for item in a.into_iter() {
471            out.push(from_rb(item)?);
472        }
473        return Ok(Value::Array(out));
474    }
475    if let Some(h) = RHash::from_value(v) {
476        let mut map = Map::new();
477        let mut pairs = Vec::new();
478        let mut string_keys = true;
479        h.foreach(|k: magnus::Value, x: magnus::Value| {
480            let value = from_rb(x).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
481            match RString::from_value(k) {
482                Some(s) => {
483                    let key = s.to_string()?;
484                    pairs.push(json!([key.clone(), value.clone()]));
485                    map.insert(key, value);
486                }
487                None => {
488                    string_keys = false;
489                    let key = from_rb(k).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
490                    pairs.push(json!([key, value]));
491                }
492            }
493            Ok(magnus::r_hash::ForEach::Continue)
494        })
495        .map_err(|e| e.to_string())?;
496        return Ok(if string_keys { Value::Object(map) } else { json!({"$hash": pairs}) });
497    }
498    Err(format!("TypeError: unsupported argument {}", v.class().inspect()))
499}
500
501/// A Ruby argument as the port's parameter type.
502pub fn arg<T: serde::de::DeserializeOwned>(v: magnus::Value) -> Result<T, String> {
503    serde_json::from_value(from_rb(v)?).map_err(|e| format!("TypeError: {e}"))
504}
505
506/// A port result as a Ruby value.
507pub fn to_rb<T: serde::Serialize>(ruby: &Ruby, out: &T) -> Result<magnus::Value, magnus::Error> {
508    let value = serde_json::to_value(out).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e.to_string()))?;
509    value_to_rb(ruby, &value)
510}
511
512fn value_to_rb(ruby: &Ruby, v: &Value) -> Result<magnus::Value, magnus::Error> {
513    Ok(match v {
514        Value::Null => ruby.qnil().as_value(),
515        Value::Bool(true) => ruby.qtrue().as_value(),
516        Value::Bool(false) => ruby.qfalse().as_value(),
517        Value::Number(n) => match n.as_i64() {
518            Some(i) if !n.is_f64() => ruby.integer_from_i64(i).as_value(),
519            _ => ruby.float_from_f64(n.as_f64().unwrap_or(f64::NAN)).as_value(),
520        },
521        Value::String(s) => ruby.str_new(s).as_value(),
522        Value::Array(items) => {
523            let array = ruby.ary_new_capa(items.len());
524            for item in items {
525                array.push(value_to_rb(ruby, item)?)?;
526            }
527            array.as_value()
528        }
529        Value::Object(o) if o.len() == 1 && o.keys().next().is_some_and(|k| k.starts_with('$')) => {
530            let (key, inner) = o.iter().next().expect("one entry");
531            match key.as_str() {
532                "$num" => ruby
533                    .float_from_f64(match inner.as_str() {
534                        Some("Infinity") => f64::INFINITY,
535                        Some("-Infinity") => f64::NEG_INFINITY,
536                        Some("-0") => -0.0,
537                        _ => f64::NAN,
538                    })
539                    .as_value(),
540                "$sym" => ruby.to_symbol(inner.as_str().unwrap_or_default()).as_value(),
541                "$int" => ruby.str_new(inner.as_str().unwrap_or("0")).funcall("to_i", ())?,
542                "$hash" => {
543                    let hash = ruby.hash_new();
544                    for pair in inner.as_array().map(Vec::as_slice).unwrap_or_default() {
545                        if let Some([k, x]) = pair.as_array().map(Vec::as_slice) {
546                            hash.aset(value_to_rb(ruby, k)?, value_to_rb(ruby, x)?)?;
547                        }
548                    }
549                    hash.as_value()
550                }
551                _ => {
552                    let hash = ruby.hash_new();
553                    hash.aset(ruby.str_new(key), value_to_rb(ruby, inner)?)?;
554                    hash.as_value()
555                }
556            }
557        }
558        Value::Object(o) => {
559            let hash = ruby.hash_new();
560            for (k, x) in o {
561                hash.aset(ruby.str_new(k), value_to_rb(ruby, x)?)?;
562            }
563            hash.as_value()
564        }
565    })
566}
567"#;