rust-anything 1.5.1

Rewrite your app in Rust, one piece at a time, checked against the original's recorded behavior at every step. TypeScript/JavaScript, Python, C, Go, Ruby and Java
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Ruby: the Fiddle wrapper (the original module functions over the Rust library), and the
//! driver that calls them by name for record, diff and bench.

use std::fmt::Write as _;

use crate::bridge::Manifest;
use crate::lang::ruby::{receiver, signature};

/// JSON markers shared by the wrapper and the driver: floats JSON cannot carry, symbols,
/// hashes with non-string keys, and other objects.
const CODEC_RB: &str = r#"
module RustAnythingCodec
  module_function

  def enc(v)
    case v
    when Float
      return { "$num" => "NaN" } if v.nan?
      return { "$num" => v.positive? ? "Infinity" : "-Infinity" } if v.infinite?
      return { "$num" => "-0" } if v.zero? && (1.0 / v).negative?

      v
    when Integer, String, true, false, nil then v
    when Symbol then { "$sym" => v.to_s }
    when Array then v.map { |x| enc(x) }
    when Hash
      if v.keys.all? { |k| k.is_a?(String) }
        v.transform_values { |x| enc(x) }
      else
        { "$hash" => v.map { |k, x| [enc(k), enc(x)] } }
      end
    else
      { "$object" => v.class.name, "value" => v.respond_to?(:to_h) ? enc(v.to_h) : v.inspect }
    end
  end

  def dec(v)
    case v
    when Array then v.map { |x| dec(x) }
    when Hash
      if v.size == 1 && v.key?("$num")
        { "NaN" => Float::NAN, "Infinity" => Float::INFINITY, "-Infinity" => -Float::INFINITY, "-0" => -0.0 }.fetch(v["$num"])
      elsif v.size == 1 && v.key?("$undefined")
        nil
      elsif v.size == 1 && v.key?("$sym")
        v["$sym"].to_sym
      elsif v.size == 1 && v.key?("$hash")
        v["$hash"].to_h { |k, x| [dec(k), dec(x)] }
      else
        v.transform_values { |x| dec(x) }
      end
    else v
    end
  end
end
"#;

/// The wrapper: the same modules and module functions, each calling the Rust library.
pub fn wrapper(m: &Manifest, api: &crate::codegen::PortApi) -> Result<String, String> {
    let lib = m.lib_name();
    let mut out = native(m);
    out.push_str(&module_functions(m, &lib));
    out.push_str(&crate::codegen_batch_native::ruby_wrapper(m, api)?);
    Ok(out)
}

/// The codec and the module that calls the Rust library.
fn native(m: &Manifest) -> String {
    let lib = m.lib_name();
    format!(
        "# frozen_string_literal: true\n\n\
         # The Rust port of `{unit}`, generated by rust-anything: the same module functions, each\n\
         # calling the Rust extension `{lib}_native`. Load it in place of the original files.\n\
         # Regenerate with `rust-anything refresh`.\n\n\
         require_relative \"{lib}_native\"\n",
        unit = m.unit,
    )
}

fn module_functions(m: &Manifest, lib: &str) -> String {
    let mut out = String::new();
    let mut by_module: Vec<(String, Vec<String>)> = Vec::new();
    for f in &m.exports {
        let (recv, name) = receiver(f);
        let sig = signature(f);
        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let def = format!(
            "def self.{name}({sig})\n  RustAnythingNative{}.{}({})\nend",
            camel(lib),
            f.name,
            args.join(", ")
        );
        match by_module.iter_mut().find(|(r, _)| *r == recv) {
            Some((_, defs)) => defs.push(def),
            None => by_module.push((recv, vec![def])),
        }
    }
    for (recv, defs) in by_module {
        let parts: Vec<&str> = recv.split("::").collect();
        let mut code = String::new();
        for (depth, part) in parts.iter().enumerate() {
            let _ = writeln!(code, "{}module {part}", "  ".repeat(depth));
        }
        let indent = "  ".repeat(parts.len());
        for (i, def) in defs.iter().enumerate() {
            if i > 0 {
                code.push('\n');
            }
            for line in def.lines() {
                let _ = writeln!(code, "{indent}{line}");
            }
        }
        for depth in (0..parts.len()).rev() {
            let _ = writeln!(code, "{}end", "  ".repeat(depth));
        }
        let _ = write!(out, "\n{code}");
    }
    out
}

/// A shadow file: require it after the original. Each module function runs the original and
/// the Rust port, returns the original's result and counts mismatches. `RUST_ANYTHING_MODE=old`
/// runs the original only, `new` the port only.
pub fn shadow(m: &Manifest) -> String {
    let lib = m.lib_name();
    let call = format!("RustAnythingNative{}", camel(&lib));
    let mut out = format!(
        "# frozen_string_literal: true\n\n\
         # Runs `{unit}` and its Rust port side by side. Generated by rust-anything: require it after the\n\
         # original files. RUST_ANYTHING_MODE=old|shadow|new.\n\n\
         require \"json\"\nrequire_relative \"{lib}_native\"\n{CODEC_RB}",
        unit = m.unit,
    );
    out.push_str(
        r#"
module RustAnythingShadow
  MODE = ENV.fetch("RUST_ANYTHING_MODE", "shadow")
  @calls = 0
  @mismatches = 0

  class << self
    attr_reader :calls, :mismatches

    def compare(name, expected, actual)
      @calls += 1
      return if JSON.generate(RustAnythingCodec.enc(expected)) == JSON.generate(RustAnythingCodec.enc(actual))

      @mismatches += 1
      warn "[rust-anything] mismatch in #{name}: expected #{expected.inspect}, got #{actual.inspect}" if @mismatches <= 10
    end
  end
end
"#,
    );
    for f in &m.exports {
        let (recv, name) = receiver(f);
        let sig = signature(f);
        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
        let args = args.join(", ");
        let _ = write!(
            out,
            "
{recv}.singleton_class.prepend(Module.new do
               def {name}({sig})
                 return {call}.{fname}({args}) if RustAnythingShadow::MODE == \"new\"

                 expected = super
                 unless RustAnythingShadow::MODE == \"old\"
                   actual = begin
        {call}.{fname}({args})
                   rescue StandardError => e
        e
      end
                   RustAnythingShadow.compare(\"{recv}.{name}\", expected, actual)
    end
                 expected
  end
end)
",
            fname = f.name,
        );
    }
    out
}

pub fn camel(lib: &str) -> String {
    lib.split('_')
        .map(|p| {
            let mut c = p.chars();
            c.next()
                .map(|f| f.to_uppercase().chain(c).collect::<String>())
                .unwrap_or_default()
        })
        .collect()
}

/// `{ name: [receiver, method] }` for the driver.
pub fn targets(m: &Manifest) -> serde_json::Value {
    serde_json::Value::Object(
        m.exports
            .iter()
            .map(|f| {
                let (recv, name) = receiver(f);
                (f.name.clone(), serde_json::json!([recv, name]))
            })
            .collect(),
    )
}

pub fn driver() -> String {
    format!("{CODEC_RB}\n{DRIVER_RB}")
}

const DRIVER_RB: &str = r#"
require "json"

mode, targets_path, cases_path, out_path, min_ms, *files = ARGV
files.each { |f| require f }
TARGETS = JSON.parse(File.read(targets_path))

def call(c)
  recv, name = TARGETS.fetch(c["fn"])
  args = (c["args"] || []).dup
  args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
  args = RustAnythingCodec.dec(args)
  kwargs = RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)
  value = Object.const_get(recv).public_send(name, *args, **kwargs)
  { "ok" => RustAnythingCodec.enc(value) }
rescue StandardError, ScriptError => e
  { "error" => e.message, "error_type" => e.class.name }
end

def lines(path)
  File.readlines(path, chomp: true).reject(&:empty?).map { |l| JSON.parse(l) }
end

def same?(expected, got)
  return false if got["error"].to_s.start_with?("Rust panic:")
  return got.key?("error") && expected["error_type"] == got["error_type"] if expected.key?("error")

  !got.key?("error") && JSON.generate(expected["ok"]) == JSON.generate(got["ok"])
end

case mode
when "record"
  progress = ENV["RUST_ANYTHING_PROGRESS"]
  File.open(out_path, "w") do |out|
    JSON.parse(File.read(cases_path)).each_with_index do |c, index|
      File.open(progress, "a") { |p| p.puts(index) } if progress
      line = { "fn" => c["fn"], "args" => c["args"] }
      line["kwargs"] = c["kwargs"] if c["kwargs"]
      line.merge!(call(c))
      begin
        out.puts(JSON.generate(line))
        out.flush
      rescue JSON::GeneratorError, Encoding::UndefinedConversionError
        next
      end
    end
  end
when "diff"
  summary = { "total" => 0, "passed" => 0, "failed" => 0, "missing" => [], "mismatches" => [] }
  lines(cases_path).each do |c|
    summary["total"] += 1
    got = call(c)
    expected = c.slice("ok", "error", "error_type")
    if same?(expected, got)
      summary["passed"] += 1
    else
      summary["failed"] += 1
      shown = c["kwargs"].nil? || c["kwargs"].empty? ? c["args"] : c["args"] + [c["kwargs"]]
      summary["mismatches"] << { "fn" => c["fn"], "args" => shown, "expected" => expected, "actual" => got }
    end
  end
  File.write(out_path, JSON.generate(summary))
when "bench"
  groups = lines(cases_path).group_by { |c| c["fn"] }
  result = {}
  groups.each do |name, cases|
    # Arguments are decoded once, the method looked up once: only the calls are timed.
    recv, meth = TARGETS.fetch(name)
    target = Object.const_get(recv).method(meth)
    prepared = cases.map do |c|
      args = (c["args"] || []).dup
      args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
      [RustAnythingCodec.dec(args), RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)]
    end
    once = lambda do
      prepared.each do |args, kwargs|
        target.call(*args, **kwargs)
      rescue StandardError
        nil
      end
    end
    once.call
    passes = 0
    start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
    loop do
      once.call
      passes += 1
      elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
      if elapsed * 1000 >= min_ms.to_i
        result[name] = { "cases" => cases.size, "ns" => elapsed * 1e9 / (passes * cases.size) }
        break
      end
    end
  end
  File.write(out_path, JSON.generate(result))
end
"#;

/// Whether a port type holds `serde_json::Value`: such values convert through `rbconv.rs`;
/// everything else (strings, numbers, booleans, `Vec`, `Option`, `HashMap`) converts directly.
fn via_json(ty: &str) -> bool {
    ty.contains("Value")
}

/// `src/lib.rs` of a Ruby crate: a magnus extension defining `RustAnythingNative<Lib>` with one
/// module function per port function, positional arguments only (the Ruby wrapper keeps the
/// original defaults and keywords).
pub fn lib_rs(m: &Manifest, api: &crate::codegen::PortApi) -> Result<String, String> {
    let lib = m.lib_name();
    let mut out = format!(
        "//! Ruby extension for `{unit}`, generated by rust-anything from `src/port.rs`. Regenerate with\n\
         //! `rust-anything refresh`. Values convert directly between Ruby and Rust: no JSON.\n\n\
         use magnus::{{Error, ExceptionClass, Module, Object, Ruby, function, method}};\n\
         #[allow(unused_imports)]\nuse serde_json::Value;\n\n\
         pub mod port;\nmod rbconv;\n\n\
         /// `Err(\"ArgumentError: message\")` raises that exception class; otherwise a RuntimeError.\n\
         fn error(ruby: &Ruby, message: String) -> Error {{\n    \
         if let Some((kind, text)) = message.split_once(\": \")\n        \
         && kind.starts_with(|c: char| c.is_ascii_uppercase())\n        \
         && kind.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')\n        \
         && let Ok(class) = ruby.class_object().const_get::<_, ExceptionClass>(kind)\n    {{\n        \
         return Error::new(class, text.to_string());\n    }}\n    \
         Error::new(ruby.exception_runtime_error(), message)\n}}\n\n\
         /// Runs the port; a panic becomes a RuntimeError instead of Ruby's uncatchable `fatal`.\n\
         fn guard<T>(ruby: &Ruby, f: impl FnOnce() -> Result<T, String>) -> Result<T, Error> {{\n    \
         match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {{\n        \
         Ok(result) => result.map_err(|m| error(ruby, m)),\n        \
         Err(panic) => {{\n            \
         let text = panic\n                .downcast_ref::<&str>()\n                .map(ToString::to_string)\n                \
         .or_else(|| panic.downcast_ref::<String>().cloned())\n                .unwrap_or_default();\n            \
         Err(Error::new(ruby.exception_runtime_error(), format!(\"Rust panic: {{text}}\")))\n        }}\n    }}\n}}\n",
        unit = m.unit,
    );
    let mut defs = Vec::new();
    for f in &api.functions {
        let params: Vec<String> = f
            .params
            .iter()
            .map(|(n, t)| {
                if via_json(t) {
                    format!("{n}: magnus::Value")
                } else {
                    format!("{n}: {t}")
                }
            })
            .collect();
        let mut body = String::new();
        for (n, t) in f.params.iter().filter(|(_, t)| via_json(t)) {
            let _ = writeln!(
                body,
                "    let {n}: {t} = rbconv::arg({n}).map_err(|m| error(ruby, m))?;"
            );
        }
        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
        let call = format!("port::{}({})", f.rust_name, args.join(", "));
        let call = if f.fallible {
            call
        } else {
            format!("Ok({call})")
        };
        let (ret, tail) = if f.ret == "()" {
            ("()".to_string(), "")
        } else if via_json(&f.ret) {
            (
                "magnus::Value".to_string(),
                "\n        .and_then(|out| rbconv::to_rb(ruby, &out))",
            )
        } else {
            (f.ret.clone(), "")
        };
        let rb_name = format!("rb_{}", f.rust_name.trim_start_matches("r#"));
        let ruby_param = if params.is_empty() {
            "ruby: &Ruby".to_string()
        } else {
            format!("ruby: &Ruby, {}", params.join(", "))
        };
        let _ = writeln!(
            out,
            "\n/// `{js}`.\nfn {rb_name}({ruby_param}) -> Result<{ret}, Error> {{\n{body}    guard(ruby, || {call}){tail}\n}}",
            js = f.js_name,
        );
        defs.push(format!(
            "    native.define_module_function(\"{}\", function!({rb_name}, {}))?;",
            f.js_name,
            f.params.len()
        ));
    }
    let (batches, batch_init) = crate::codegen_batch_native::ruby_rs(m, api)?;
    out.push_str(&batches);
    let _ = writeln!(
        out,
        "\n#[magnus::init(name = \"{lib}_native\")]\nfn init(ruby: &Ruby) -> Result<(), Error> {{\n    \
         let native = ruby.define_module(\"RustAnythingNative{camel}\")?;\n{}\n{batch_init}    Ok(())\n}}",
        defs.join("\n"),
        camel = camel(&lib),
    );
    Ok(out)
}

pub fn cargo_toml(m: &Manifest) -> String {
    format!(
        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\npublish = false\n\
         description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
         [lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\nmagnus = \"0.8\"\n\
         serde = {{ version = \"1\", features = [\"derive\"] }}\n\
         serde_json = {{ version = \"1\", features = [\"preserve_order\", \"float_roundtrip\"] }}\n\n\
         [profile.release]\nlto = true\n\n[lints.clippy]\nall = {{ level = \"warn\", priority = -1 }}\n",
        m.crate_name, m.unit
    )
}

/// `src/rbconv.rs`: Ruby values to `serde_json::Value` and back, with the markers recorded
/// cases use (`$num`, `$sym`, `$hash`, `$int`).
pub const RBCONV_RS: &str = r#"//! Ruby values to `serde_json::Value` and back, in Rust. Generated by rust-anything.

// Ports without dynamic values use only some of these.
#![allow(dead_code)]

use magnus::{Float, Integer, RArray, RHash, RString, Ruby, Symbol, value::ReprValue};
use serde_json::{Map, Value, json};

/// A Ruby value as JSON.
pub fn from_rb(v: magnus::Value) -> Result<Value, String> {
    let ruby = Ruby::get().map_err(|e| e.to_string())?;
    if v.is_nil() {
        return Ok(Value::Null);
    }
    if v.is_kind_of(ruby.class_true_class()) {
        return Ok(Value::Bool(true));
    }
    if v.is_kind_of(ruby.class_false_class()) {
        return Ok(Value::Bool(false));
    }
    if let Some(i) = Integer::from_value(v) {
        return Ok(match i.to_i64() {
            Ok(n) => json!(n),
            Err(_) => json!({"$int": v.funcall::<_, _, String>("to_s", ()).map_err(|e| e.to_string())?}),
        });
    }
    if let Some(f) = Float::from_value(v) {
        let x = f.to_f64();
        return Ok(if x.is_nan() {
            json!({"$num": "NaN"})
        } else if x.is_infinite() {
            json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
        } else if x == 0.0 && x.is_sign_negative() {
            json!({"$num": "-0"})
        } else {
            json!(x)
        });
    }
    if let Some(s) = RString::from_value(v) {
        return s.to_string().map(Value::String).map_err(|e| e.to_string());
    }
    if let Some(s) = Symbol::from_value(v) {
        return Ok(json!({"$sym": s.name().map_err(|e| e.to_string())?}));
    }
    if let Some(a) = RArray::from_value(v) {
        let mut out = Vec::with_capacity(a.len());
        for item in a.into_iter() {
            out.push(from_rb(item)?);
        }
        return Ok(Value::Array(out));
    }
    if let Some(h) = RHash::from_value(v) {
        let mut map = Map::new();
        let mut pairs = Vec::new();
        let mut string_keys = true;
        h.foreach(|k: magnus::Value, x: magnus::Value| {
            let value = from_rb(x).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
            match RString::from_value(k) {
                Some(s) => {
                    let key = s.to_string()?;
                    pairs.push(json!([key.clone(), value.clone()]));
                    map.insert(key, value);
                }
                None => {
                    string_keys = false;
                    let key = from_rb(k).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
                    pairs.push(json!([key, value]));
                }
            }
            Ok(magnus::r_hash::ForEach::Continue)
        })
        .map_err(|e| e.to_string())?;
        return Ok(if string_keys { Value::Object(map) } else { json!({"$hash": pairs}) });
    }
    Err(format!("TypeError: unsupported argument {}", v.class().inspect()))
}

/// A Ruby argument as the port's parameter type.
pub fn arg<T: serde::de::DeserializeOwned>(v: magnus::Value) -> Result<T, String> {
    serde_json::from_value(from_rb(v)?).map_err(|e| format!("TypeError: {e}"))
}

/// A port result as a Ruby value.
pub fn to_rb<T: serde::Serialize>(ruby: &Ruby, out: &T) -> Result<magnus::Value, magnus::Error> {
    let value = serde_json::to_value(out).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e.to_string()))?;
    value_to_rb(ruby, &value)
}

fn value_to_rb(ruby: &Ruby, v: &Value) -> Result<magnus::Value, magnus::Error> {
    Ok(match v {
        Value::Null => ruby.qnil().as_value(),
        Value::Bool(true) => ruby.qtrue().as_value(),
        Value::Bool(false) => ruby.qfalse().as_value(),
        Value::Number(n) => match n.as_i64() {
            Some(i) if !n.is_f64() => ruby.integer_from_i64(i).as_value(),
            _ => ruby.float_from_f64(n.as_f64().unwrap_or(f64::NAN)).as_value(),
        },
        Value::String(s) => ruby.str_new(s).as_value(),
        Value::Array(items) => {
            let array = ruby.ary_new_capa(items.len());
            for item in items {
                array.push(value_to_rb(ruby, item)?)?;
            }
            array.as_value()
        }
        Value::Object(o) if o.len() == 1 && o.keys().next().is_some_and(|k| k.starts_with('$')) => {
            let (key, inner) = o.iter().next().expect("one entry");
            match key.as_str() {
                "$num" => ruby
                    .float_from_f64(match inner.as_str() {
                        Some("Infinity") => f64::INFINITY,
                        Some("-Infinity") => f64::NEG_INFINITY,
                        Some("-0") => -0.0,
                        _ => f64::NAN,
                    })
                    .as_value(),
                "$sym" => ruby.to_symbol(inner.as_str().unwrap_or_default()).as_value(),
                "$int" => ruby.str_new(inner.as_str().unwrap_or("0")).funcall("to_i", ())?,
                "$hash" => {
                    let hash = ruby.hash_new();
                    for pair in inner.as_array().map(Vec::as_slice).unwrap_or_default() {
                        if let Some([k, x]) = pair.as_array().map(Vec::as_slice) {
                            hash.aset(value_to_rb(ruby, k)?, value_to_rb(ruby, x)?)?;
                        }
                    }
                    hash.as_value()
                }
                _ => {
                    let hash = ruby.hash_new();
                    hash.aset(ruby.str_new(key), value_to_rb(ruby, inner)?)?;
                    hash.as_value()
                }
            }
        }
        Value::Object(o) => {
            let hash = ruby.hash_new();
            for (k, x) in o {
                hash.aset(ruby.str_new(k), value_to_rb(ruby, x)?)?;
            }
            hash.as_value()
        }
    })
}
"#;