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