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 {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 mut code = reopen(&recv);
101        let _ = writeln!(code, "class << {recv}");
102        for (i, def) in defs.iter().enumerate() {
103            if i > 0 {
104                code.push('\n');
105            }
106            for line in def.lines() {
107                let _ = writeln!(code, "  {line}");
108            }
109        }
110        code.push_str("end\n");
111        let _ = write!(out, "\n{code}");
112    }
113    out
114}
115
116/// Lines that make each module of `A::B` that is not defined yet, so the wrapper can reopen a
117/// receiver that the original made a class (loaded first in replays) as well as a module.
118pub(crate) fn reopen(recv: &str) -> String {
119    let parts: Vec<&str> = recv.split("::").collect();
120    let mut code = String::new();
121    for i in 1..=parts.len() {
122        let path = parts[..i].join("::");
123        let _ = writeln!(code, "module {path}; end unless defined?(::{path})");
124    }
125    code
126}
127
128/// A shadow file: require it after the original. Each module function runs the original and
129/// the Rust port, returns the original's result and counts mismatches. `RUST_ANYTHING_MODE=old`
130/// runs the original only, `new` the port only.
131pub fn shadow(m: &Manifest) -> String {
132    let lib = m.lib_name();
133    let call = format!("RustAnythingNative{}", camel(&lib));
134    let mut out = format!(
135        "# frozen_string_literal: true\n\n\
136         # Runs `{unit}` and its Rust port side by side. Generated by rust-anything: require it after the\n\
137         # original files. RUST_ANYTHING_MODE=old|shadow|new.\n\n\
138         require \"json\"\nrequire_relative \"{lib}_native\"\n{CODEC_RB}",
139        unit = m.unit,
140    );
141    out.push_str(
142        r#"
143module RustAnythingShadow
144  MODE = ENV.fetch("RUST_ANYTHING_MODE", "shadow")
145  @calls = 0
146  @mismatches = 0
147
148  class << self
149    attr_reader :calls, :mismatches
150
151    def compare(name, expected, actual)
152      @calls += 1
153      return if JSON.generate(RustAnythingCodec.enc(expected)) == JSON.generate(RustAnythingCodec.enc(actual))
154
155      @mismatches += 1
156      warn "[rust-anything] mismatch in #{name}: expected #{expected.inspect}, got #{actual.inspect}" if @mismatches <= 10
157    end
158  end
159end
160"#,
161    );
162    for f in &m.exports {
163        let (recv, name) = receiver(f);
164        let sig = signature(f);
165        let args: Vec<&str> = f.params.iter().map(|p| p.name.as_str()).collect();
166        let args = args.join(", ");
167        let _ = write!(
168            out,
169            "
170{recv}.singleton_class.prepend(Module.new do
171               def {name}({sig})
172                 return {call}.{fname}({args}) if RustAnythingShadow::MODE == \"new\"
173
174                 expected = super
175                 unless RustAnythingShadow::MODE == \"old\"
176                   actual = begin
177        {call}.{fname}({args})
178                   rescue StandardError => e
179        e
180      end
181                   RustAnythingShadow.compare(\"{recv}.{name}\", expected, actual)
182    end
183                 expected
184  end
185end)
186",
187            fname = f.name,
188        );
189    }
190    out
191}
192
193pub fn camel(lib: &str) -> String {
194    lib.split('_')
195        .map(|p| {
196            let mut c = p.chars();
197            c.next()
198                .map(|f| f.to_uppercase().chain(c).collect::<String>())
199                .unwrap_or_default()
200        })
201        .collect()
202}
203
204/// `{ name: [receiver, method] }` for the driver.
205pub fn targets(m: &Manifest) -> serde_json::Value {
206    serde_json::Value::Object(
207        m.exports
208            .iter()
209            .map(|f| {
210                let (recv, name) = receiver(f);
211                (f.name.clone(), serde_json::json!([recv, name]))
212            })
213            .collect(),
214    )
215}
216
217pub fn driver() -> String {
218    format!("{CODEC_RB}\n{DRIVER_RB}")
219}
220
221const DRIVER_RB: &str = r#"
222require "json"
223
224mode, targets_path, cases_path, out_path, min_ms, *files = ARGV
225files.each { |f| require f }
226TARGETS = JSON.parse(File.read(targets_path))
227
228def call(c)
229  recv, name = TARGETS.fetch(c["fn"])
230  args = (c["args"] || []).dup
231  args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
232  args = RustAnythingCodec.dec(args)
233  kwargs = RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)
234  value = Object.const_get(recv).public_send(name, *args, **kwargs)
235  { "ok" => RustAnythingCodec.enc(value) }
236rescue StandardError, ScriptError => e
237  { "error" => e.message, "error_type" => e.class.name }
238end
239
240def lines(path)
241  File.readlines(path, chomp: true).reject(&:empty?).map { |l| JSON.parse(l) }
242end
243
244def same?(expected, got)
245  return false if got["error"].to_s.start_with?("Rust panic:")
246  return got.key?("error") && expected["error_type"] == got["error_type"] if expected.key?("error")
247
248  !got.key?("error") && JSON.generate(expected["ok"]) == JSON.generate(got["ok"])
249end
250
251def wrapper_error(fn_name, wrapper)
252  return nil if wrapper.nil? || wrapper.empty?
253
254  recv, name = TARGETS.fetch(fn_name)
255  loc = Object.const_get(recv).method(name).source_location&.first
256  return nil if loc && File.realpath(loc) == File.realpath(wrapper)
257
258  { "error" => "wrapper did not override #{recv}.#{name} (got #{loc.inspect}, expected #{wrapper.inspect})", "error_type" => "RuntimeError" }
259rescue KeyError, NameError, SystemCallError => e
260  { "error" => e.message, "error_type" => e.class.name }
261end
262
263case mode
264when "record"
265  progress = ENV["RUST_ANYTHING_PROGRESS"]
266  File.open(out_path, "w") do |out|
267    JSON.parse(File.read(cases_path)).each_with_index do |c, index|
268      File.open(progress, "a") { |p| p.puts(index) } if progress
269      line = { "fn" => c["fn"], "args" => c["args"] }
270      line["kwargs"] = c["kwargs"] if c["kwargs"]
271      line.merge!(call(c))
272      begin
273        out.puts(JSON.generate(line))
274        out.flush
275      rescue JSON::GeneratorError, Encoding::UndefinedConversionError
276        next
277      end
278    end
279  end
280when "diff"
281  wrapper = ENV["RUST_ANYTHING_WRAPPER"]
282  summary = { "total" => 0, "passed" => 0, "failed" => 0, "missing" => [], "mismatches" => [] }
283  lines(cases_path).each do |c|
284    summary["total"] += 1
285    expected = c.slice("ok", "error", "error_type")
286    mismatch = wrapper_error(c["fn"], wrapper)
287    got = mismatch || call(c)
288    if mismatch.nil? && same?(expected, got)
289      summary["passed"] += 1
290    else
291      summary["failed"] += 1
292      shown = c["kwargs"].nil? || c["kwargs"].empty? ? c["args"] : c["args"] + [c["kwargs"]]
293      summary["mismatches"] << { "fn" => c["fn"], "args" => shown, "expected" => expected, "actual" => got }
294    end
295  end
296  File.write(out_path, JSON.generate(summary))
297when "bench"
298  groups = lines(cases_path).group_by { |c| c["fn"] }
299  result = {}
300  groups.each do |name, cases|
301    # Arguments are decoded once, the method looked up once: only the calls are timed.
302    recv, meth = TARGETS.fetch(name)
303    target = Object.const_get(recv).method(meth)
304    prepared = cases.map do |c|
305      args = (c["args"] || []).dup
306      args.pop while args.any? && args.last.is_a?(Hash) && args.last.key?("$undefined")
307      [RustAnythingCodec.dec(args), RustAnythingCodec.dec(c["kwargs"] || {}).transform_keys(&:to_sym)]
308    end
309    once = lambda do
310      prepared.each do |args, kwargs|
311        target.call(*args, **kwargs)
312      rescue StandardError
313        nil
314      end
315    end
316    once.call
317    passes = 0
318    start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
319    loop do
320      once.call
321      passes += 1
322      elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start
323      if elapsed * 1000 >= min_ms.to_i
324        result[name] = { "cases" => cases.size, "ns" => elapsed * 1e9 / (passes * cases.size) }
325        break
326      end
327    end
328  end
329  File.write(out_path, JSON.generate(result))
330end
331"#;
332
333/// Whether a port type holds `serde_json::Value`: such values convert through `rbconv.rs`;
334/// everything else (strings, numbers, booleans, `Vec`, `Option`, `HashMap`) converts directly.
335fn via_json(ty: &str) -> bool {
336    ty.contains("Value")
337}
338
339/// `src/lib.rs` of a Ruby crate: a magnus extension defining `RustAnythingNative<Lib>` with one
340/// module function per port function, positional arguments only (the Ruby wrapper keeps the
341/// original defaults and keywords).
342pub fn lib_rs(m: &Manifest, api: &crate::codegen::PortApi) -> Result<String, String> {
343    let lib = m.lib_name();
344    let mut out = format!(
345        "//! Ruby extension for `{unit}`, generated by rust-anything from `src/port.rs`. Regenerate with\n\
346         //! `rust-anything refresh`. Values convert directly between Ruby and Rust: no JSON.\n\n\
347         use magnus::{{Error, ExceptionClass, Module, Object, Ruby, function, method, value::ReprValue}};\n\
348         #[allow(unused_imports)]\nuse serde_json::Value;\n\n\
349         pub mod port;\nmod rbconv;\n\n\
350         /// Resolves a `::`-separated constant path like `\"Textkit::ParseError\"` to an `Exception` subclass.\n\
351         fn resolve_exception(ruby: &Ruby, kind: &str) -> Option<ExceptionClass> {{\n    \
352         let mut parts = kind.split(\"::\").peekable();\n    \
353         let mut cur = ruby.class_object().as_value();\n    \
354         let mut first = true;\n    \
355         while let Some(part) = parts.next() {{\n        \
356         if !part.starts_with(|c: char| c.is_ascii_uppercase())\n            \
357         || !part.chars().all(|c| c.is_ascii_alphanumeric() || c == '_')\n        \
358         {{\n            \
359         return None;\n        \
360         }}\n        \
361         if parts.peek().is_none() {{\n            \
362         let class: ExceptionClass = if first {{\n                \
363         cur.funcall(\"const_get\", (part,)).ok()?\n            \
364         }} else {{\n                \
365         cur.funcall(\"const_get\", (part, false)).ok()?\n            \
366         }};\n            \
367         let exc = ruby\n                \
368         .class_object()\n                \
369         .const_get::<_, magnus::Value>(\"Exception\")\n                \
370         .ok()?;\n            \
371         if class.as_value().funcall::<_, _, Option<bool>>(\"<=\", (exc,)).ok().flatten() != Some(true) {{\n                \
372         return None;\n            \
373         }}\n            \
374         return Some(class);\n        \
375         }}\n        \
376         cur = if first {{\n            \
377         first = false;\n            \
378         cur.funcall(\"const_get\", (part,)).ok()?\n        \
379         }} else {{\n            \
380         cur.funcall(\"const_get\", (part, false)).ok()?\n        \
381         }};\n        \
382         if magnus::RModule::from_value(cur).is_none()\n            \
383         && magnus::RClass::from_value(cur).is_none()\n        \
384         {{\n            \
385         return None;\n        \
386         }}\n    \
387         }}\n    \
388         None\n\
389         }}\n\n\
390         /// `Err(\"ArgumentError: message\")` raises that exception class; otherwise a RuntimeError.\n\
391         fn error(ruby: &Ruby, message: String) -> Error {{\n    \
392         if let Some((kind, text)) = message.split_once(\": \")\n        \
393         && let Some(class) = resolve_exception(ruby, kind)\n    \
394         {{\n        \
395         return Error::new(class, text.to_string());\n    \
396         }}\n    \
397         Error::new(ruby.exception_runtime_error(), message)\n\
398         }}\n\n\
399         /// Runs the port; a panic becomes a RuntimeError instead of Ruby's uncatchable `fatal`.\n\
400         fn guard<T>(ruby: &Ruby, f: impl FnOnce() -> Result<T, String>) -> Result<T, Error> {{\n    \
401         match std::panic::catch_unwind(std::panic::AssertUnwindSafe(f)) {{\n        \
402         Ok(result) => result.map_err(|m| error(ruby, m)),\n        \
403         Err(panic) => {{\n            \
404         let text = panic\n                .downcast_ref::<&str>()\n                .map(ToString::to_string)\n                \
405         .or_else(|| panic.downcast_ref::<String>().cloned())\n                .unwrap_or_default();\n            \
406         Err(Error::new(ruby.exception_runtime_error(), format!(\"Rust panic: {{text}}\")))\n        }}\n    }}\n}}\n",
407        unit = m.unit,
408    );
409    let mut defs = Vec::new();
410    for f in &api.functions {
411        let params: Vec<String> = f
412            .params
413            .iter()
414            .map(|(n, t)| {
415                if via_json(t) {
416                    format!("{n}: magnus::Value")
417                } else {
418                    format!("{n}: {t}")
419                }
420            })
421            .collect();
422        let mut body = String::new();
423        for (n, t) in f.params.iter().filter(|(_, t)| via_json(t)) {
424            let _ = writeln!(
425                body,
426                "    let {n}: {t} = rbconv::arg({n}).map_err(|m| error(ruby, m))?;"
427            );
428        }
429        let args: Vec<&str> = f.params.iter().map(|(n, _)| n.as_str()).collect();
430        let call = format!("port::{}({})", f.rust_name, args.join(", "));
431        let guarded = if args.is_empty() && f.fallible {
432            format!("guard(ruby, port::{})", f.rust_name)
433        } else if f.fallible {
434            format!("guard(ruby, || {call})")
435        } else {
436            format!("guard(ruby, || Ok({call}))")
437        };
438        let (ret, tail) = if f.ret == "()" {
439            ("()".to_string(), "")
440        } else if via_json(&f.ret) {
441            (
442                "magnus::Value".to_string(),
443                "\n        .and_then(|out| rbconv::to_rb(ruby, &out))",
444            )
445        } else {
446            (f.ret.clone(), "")
447        };
448        let rb_name = format!("rb_{}", f.rust_name.trim_start_matches("r#"));
449        let ruby_param = if params.is_empty() {
450            "ruby: &Ruby".to_string()
451        } else {
452            format!("ruby: &Ruby, {}", params.join(", "))
453        };
454        let _ = writeln!(
455            out,
456            "\n/// `{js}`.\nfn {rb_name}({ruby_param}) -> Result<{ret}, Error> {{\n{body}    {guarded}{tail}\n}}",
457            js = f.js_name,
458        );
459        defs.push(format!(
460            "    native.define_module_function(\"{}\", function!({rb_name}, {}))?;",
461            f.js_name,
462            f.params.len()
463        ));
464    }
465    let (batches, batch_init) = crate::codegen_batch_native::ruby_rs(m, api)?;
466    out.push_str(&batches);
467    let _ = writeln!(
468        out,
469        "\n#[magnus::init(name = \"{lib}_native\")]\nfn init(ruby: &Ruby) -> Result<(), Error> {{\n    \
470         let native = ruby.define_module(\"RustAnythingNative{camel}\")?;\n{}\n{batch_init}    Ok(())\n}}",
471        defs.join("\n"),
472        camel = camel(&lib),
473    );
474    Ok(out)
475}
476
477pub fn cargo_toml(m: &Manifest) -> String {
478    format!(
479        "[package]\nname = \"{}\"\nversion = \"0.1.0\"\nedition = \"2024\"\nrust-version = \"{MIN_RUST}\"\npublish = false\n\
480         description = \"Rust port of `{}`, generated by rust-anything\"\n\n\
481         [lib]\ncrate-type = [\"cdylib\", \"rlib\"]\n\n[dependencies]\nmagnus = \"0.8\"\n\
482         serde = {{ version = \"1\", features = [\"derive\"] }}\n\
483         serde_json = {{ version = \"1\", features = [\"preserve_order\", \"float_roundtrip\"] }}\n\n\
484         [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",
485        m.crate_name, m.unit
486    )
487}
488
489/// `src/rbconv.rs`: Ruby values to `serde_json::Value` and back, with the markers recorded
490/// cases use (`$num`, `$sym`, `$hash`, `$int`).
491pub const RBCONV_RS: &str = r#"//! Ruby values to `serde_json::Value` and back, in Rust. Generated by rust-anything.
492
493// Ports without dynamic values use only some of these.
494#![allow(dead_code)]
495
496use magnus::{Float, Integer, RArray, RHash, RString, Ruby, Symbol, value::ReprValue};
497use serde_json::{Map, Value, json};
498
499/// A Ruby value as JSON.
500pub fn from_rb(v: magnus::Value) -> Result<Value, String> {
501    let ruby = Ruby::get().map_err(|e| e.to_string())?;
502    if v.is_nil() {
503        return Ok(Value::Null);
504    }
505    if v.is_kind_of(ruby.class_true_class()) {
506        return Ok(Value::Bool(true));
507    }
508    if v.is_kind_of(ruby.class_false_class()) {
509        return Ok(Value::Bool(false));
510    }
511    if let Some(i) = Integer::from_value(v) {
512        return Ok(match i.to_i64() {
513            Ok(n) => json!(n),
514            Err(_) => json!({"$int": v.funcall::<_, _, String>("to_s", ()).map_err(|e| e.to_string())?}),
515        });
516    }
517    if let Some(f) = Float::from_value(v) {
518        let x = f.to_f64();
519        return Ok(if x.is_nan() {
520            json!({"$num": "NaN"})
521        } else if x.is_infinite() {
522            json!({"$num": if x > 0.0 { "Infinity" } else { "-Infinity" }})
523        } else if x == 0.0 && x.is_sign_negative() {
524            json!({"$num": "-0"})
525        } else {
526            json!(x)
527        });
528    }
529    if let Some(s) = RString::from_value(v) {
530        return s.to_string().map(Value::String).map_err(|e| e.to_string());
531    }
532    if let Some(s) = Symbol::from_value(v) {
533        return Ok(json!({"$sym": s.name().map_err(|e| e.to_string())?}));
534    }
535    if let Some(a) = RArray::from_value(v) {
536        let mut out = Vec::with_capacity(a.len());
537        for item in a.into_iter() {
538            out.push(from_rb(item)?);
539        }
540        return Ok(Value::Array(out));
541    }
542    if let Some(h) = RHash::from_value(v) {
543        let mut map = Map::new();
544        let mut pairs = Vec::new();
545        let mut string_keys = true;
546        h.foreach(|k: magnus::Value, x: magnus::Value| {
547            let value = from_rb(x).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
548            match RString::from_value(k) {
549                Some(s) => {
550                    let key = s.to_string()?;
551                    pairs.push(json!([key.clone(), value.clone()]));
552                    map.insert(key, value);
553                }
554                None => {
555                    string_keys = false;
556                    let key = from_rb(k).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e))?;
557                    pairs.push(json!([key, value]));
558                }
559            }
560            Ok(magnus::r_hash::ForEach::Continue)
561        })
562        .map_err(|e| e.to_string())?;
563        return Ok(if string_keys { Value::Object(map) } else { json!({"$hash": pairs}) });
564    }
565    Err(format!("TypeError: unsupported argument {}", v.class().inspect()))
566}
567
568/// A Ruby argument as the port's parameter type.
569pub fn arg<T: serde::de::DeserializeOwned>(v: magnus::Value) -> Result<T, String> {
570    serde_json::from_value(from_rb(v)?).map_err(|e| format!("TypeError: {e}"))
571}
572
573/// A port result as a Ruby value.
574pub fn to_rb<T: serde::Serialize>(ruby: &Ruby, out: &T) -> Result<magnus::Value, magnus::Error> {
575    let value = serde_json::to_value(out).map_err(|e| magnus::Error::new(ruby.exception_type_error(), e.to_string()))?;
576    value_to_rb(ruby, &value)
577}
578
579fn value_to_rb(ruby: &Ruby, v: &Value) -> Result<magnus::Value, magnus::Error> {
580    Ok(match v {
581        Value::Null => ruby.qnil().as_value(),
582        Value::Bool(true) => ruby.qtrue().as_value(),
583        Value::Bool(false) => ruby.qfalse().as_value(),
584        Value::Number(n) => match n.as_i64() {
585            Some(i) if !n.is_f64() => ruby.integer_from_i64(i).as_value(),
586            _ => ruby.float_from_f64(n.as_f64().unwrap_or(f64::NAN)).as_value(),
587        },
588        Value::String(s) => ruby.str_new(s).as_value(),
589        Value::Array(items) => {
590            let array = ruby.ary_new_capa(items.len());
591            for item in items {
592                array.push(value_to_rb(ruby, item)?)?;
593            }
594            array.as_value()
595        }
596        Value::Object(o) if o.len() == 1 && o.keys().next().is_some_and(|k| k.starts_with('$')) => {
597            let (key, inner) = o.iter().next().expect("one entry");
598            match key.as_str() {
599                "$num" => ruby
600                    .float_from_f64(match inner.as_str() {
601                        Some("Infinity") => f64::INFINITY,
602                        Some("-Infinity") => f64::NEG_INFINITY,
603                        Some("-0") => -0.0,
604                        _ => f64::NAN,
605                    })
606                    .as_value(),
607                "$sym" => ruby.to_symbol(inner.as_str().unwrap_or_default()).as_value(),
608                "$int" => ruby.str_new(inner.as_str().unwrap_or("0")).funcall("to_i", ())?,
609                "$hash" => {
610                    let hash = ruby.hash_new();
611                    for pair in inner.as_array().map(Vec::as_slice).unwrap_or_default() {
612                        if let Some([k, x]) = pair.as_array().map(Vec::as_slice) {
613                            hash.aset(value_to_rb(ruby, k)?, value_to_rb(ruby, x)?)?;
614                        }
615                    }
616                    hash.as_value()
617                }
618                _ => {
619                    let hash = ruby.hash_new();
620                    hash.aset(ruby.str_new(key), value_to_rb(ruby, inner)?)?;
621                    hash.as_value()
622                }
623            }
624        }
625        Value::Object(o) => {
626            let hash = ruby.hash_new();
627            for (k, x) in o {
628                hash.aset(ruby.str_new(k), value_to_rb(ruby, x)?)?;
629            }
630            hash.as_value()
631        }
632    })
633}
634"#;
635
636#[cfg(test)]
637mod tests {
638    use super::*;
639
640    #[test]
641    fn lib_rs_resolves_namespaced_ruby_exceptions() {
642        let m = Manifest {
643            schema: String::new(),
644            root: std::path::PathBuf::new(),
645            root_written: None,
646            unit: "lib/textkit/nums.rb".into(),
647            language: crate::lang::Lang::Ruby,
648            kind: crate::bridge::Kind::Ffi,
649            crate_name: "textkit-rs".into(),
650            exports: Vec::new(),
651            classes: Vec::new(),
652            js_only: Vec::new(),
653            batches: Vec::new(),
654            allocator: Default::default(),
655            float_tolerance: None,
656            ignore_key_order: false,
657        };
658        let rs = lib_rs(&m, &crate::codegen::PortApi::default()).unwrap();
659        assert!(rs.contains("fn resolve_exception("), "{rs}");
660        assert!(rs.contains("split(\"::\")"), "{rs}");
661        assert!(rs.contains("value::ReprValue"), "{rs}");
662        assert!(rs.contains("const_get\", (part, false)"), "{rs}");
663    }
664
665    #[test]
666    fn lib_rs_avoids_redundant_closure_for_zero_arg_fallible_functions() {
667        let m = Manifest {
668            schema: String::new(),
669            root: std::path::PathBuf::new(),
670            root_written: None,
671            unit: "lib/ping.rb".into(),
672            language: crate::lang::Lang::Ruby,
673            kind: crate::bridge::Kind::Ffi,
674            crate_name: "ping-rs".into(),
675            exports: Vec::new(),
676            classes: Vec::new(),
677            js_only: Vec::new(),
678            batches: Vec::new(),
679            allocator: Default::default(),
680            float_tolerance: None,
681            ignore_key_order: false,
682        };
683        let api = crate::codegen::parse_port(
684            "pub fn pong() -> Result<String, String> { Ok(\"pong\".into()) }\n\
685             pub fn pure_pong() -> String { \"pong\".into() }\n\
686             pub fn echo(s: String) -> Result<String, String> { Ok(s) }\n",
687        );
688        let rs = lib_rs(&m, &api).unwrap();
689        assert!(rs.contains("guard(ruby, port::pong)"), "{rs}");
690        assert!(!rs.contains("guard(ruby, || port::pong())"), "{rs}");
691        assert!(rs.contains("guard(ruby, || Ok(port::pure_pong()))"), "{rs}");
692        assert!(rs.contains("guard(ruby, || port::echo(s))"), "{rs}");
693    }
694}