Skip to main content

rust_anything/
harness_ruby.rs

1//! The Ruby side of record, build, diff and bench. A generated driver calls the module
2//! functions by name: with the original files loaded to record, and with the Fiddle wrapper
3//! over the Rust library loaded to diff.
4
5use crate::walk::Canonical;
6use std::path::{Path, PathBuf};
7use std::process::Command;
8
9use anyhow::{Context, Result, bail};
10use serde_json::Value;
11
12use crate::bridge::Manifest;
13use crate::harness::{BenchRow, CASES, DiffOutcome};
14
15const WORK_DIR: &str = ".rust-anything";
16
17fn run(cmd: &mut Command, what: &str) -> Result<()> {
18    let _scratch = crate::harness::scratch_cwd(cmd)?;
19    let output = cmd.output().with_context(|| format!("running {what}"))?;
20    if !output.status.success() {
21        let stderr = String::from_utf8_lossy(&output.stderr);
22        let tail: Vec<&str> = stderr.lines().rev().take(30).collect();
23        bail!(
24            "{what} failed ({}):\n{}",
25            output.status,
26            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
27        );
28    }
29    Ok(())
30}
31
32/// The wrapper file, relative to the crate.
33pub fn wrapper_path(m: &Manifest) -> String {
34    format!("ruby/{}.rb", m.lib_name())
35}
36
37/// The files to load: the unit's sources, or the wrapper.
38fn files(crate_dir: &Path, m: &Manifest, rust: bool) -> Result<Vec<PathBuf>> {
39    if rust {
40        return Ok(vec![crate_dir.join(wrapper_path(m)).canonical()?]);
41    }
42    let mut files: Vec<PathBuf> = m
43        .exports
44        .iter()
45        .map(|f| m.root.join(&f.file))
46        .chain(m.js_only.iter().map(|j| m.root.join(&j.file)))
47        .collect();
48    files.sort();
49    files.dedup();
50    Ok(files)
51}
52
53fn driver(
54    crate_dir: &Path,
55    m: &Manifest,
56    mode: &str,
57    cases: &Path,
58    out: &Path,
59    min_ms: u64,
60    rust: bool,
61) -> Result<()> {
62    let mut cmd = driver_command(crate_dir, m, mode, cases, out, min_ms, rust)?;
63    run(&mut cmd, &format!("ruby driver ({mode})"))
64}
65
66fn driver_command(
67    crate_dir: &Path,
68    m: &Manifest,
69    mode: &str,
70    cases: &Path,
71    out: &Path,
72    min_ms: u64,
73    rust: bool,
74) -> Result<Command> {
75    let work = crate_dir.join(WORK_DIR);
76    std::fs::create_dir_all(&work)?;
77    let script = work.join("driver.rb");
78    std::fs::write(&script, crate::codegen_ruby::driver())?;
79    let targets = work.join("targets.json");
80    std::fs::write(&targets, crate::codegen_ruby::targets(m).to_string())?;
81    let mut cmd = Command::new("ruby");
82    // Source and data are UTF-8 whatever the machine's locale says.
83    cmd.args(["-E", "UTF-8:UTF-8"]);
84    // The original's `require "name"` finds its own files through each package's lib folder.
85    if !rust && let Ok(ws) = crate::lang::ruby::discover(&m.root) {
86        for p in &ws.packages {
87            cmd.arg(format!("-I{}", m.root.join(&p.src_root).display()));
88        }
89    }
90    cmd.arg(&script)
91        .arg(mode)
92        .arg(&targets)
93        .arg(cases)
94        .arg(out)
95        .arg(min_ms.to_string())
96        .args(files(crate_dir, m, rust)?);
97    Ok(cmd)
98}
99
100pub fn record(crate_dir: &Path, m: &Manifest, cases: &[Value]) -> Result<PathBuf> {
101    let out = crate_dir.join(CASES);
102    let pending = crate_dir.join(WORK_DIR).join("recording.jsonl");
103    crate::harness::record_cases(
104        cases,
105        &crate_dir.join(WORK_DIR),
106        &pending,
107        "ruby driver (record)",
108        |inputs, part| driver_command(crate_dir, m, "record", inputs, part, 0, false),
109    )?;
110    let recorded: std::collections::HashSet<String> = std::fs::read_to_string(&pending)?
111        .lines()
112        .filter_map(|l| serde_json::from_str::<Value>(l).ok())
113        .filter_map(|c| c["fn"].as_str().map(str::to_string))
114        .collect();
115    let mut asked: Vec<&str> = cases.iter().filter_map(|c| c["fn"].as_str()).collect();
116    asked.sort_unstable();
117    asked.dedup();
118    if let Some(name) = asked.into_iter().find(|name| !recorded.contains(*name)) {
119        bail!(
120            "cannot encode recorded result for {name}: no case could be written as JSON \
121             (a binary String result?); kept the previous {CASES}"
122        );
123    }
124    std::fs::rename(&pending, &out).with_context(|| format!("publishing {}", out.display()))?;
125    Ok(out)
126}
127
128pub fn diff(crate_dir: &Path, m: &Manifest) -> Result<DiffOutcome> {
129    let cases = crate_dir.join(CASES);
130    if !cases.exists() {
131        bail!(
132            "no {CASES} in {} (run `rust-anything record` first)",
133            crate_dir.display()
134        );
135    }
136    let out = crate_dir.join(WORK_DIR).join("diff.json");
137    driver(crate_dir, m, "diff", &cases, &out, 0, true)?;
138    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
139}
140
141pub fn bench(crate_dir: &Path, m: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
142    let cases = crate_dir.join(CASES);
143    if !cases.exists() {
144        bail!(
145            "no {CASES} in {} (run `rust-anything record` first)",
146            crate_dir.display()
147        );
148    }
149    let mut timings = Vec::new();
150    for rust in [false, true] {
151        let out = crate_dir.join(WORK_DIR).join(if rust {
152            "bench-rust.json"
153        } else {
154            "bench-original.json"
155        });
156        driver(crate_dir, m, "bench", &cases, &out, min_ms, rust)?;
157        timings.push(serde_json::from_str(&std::fs::read_to_string(&out)?)?);
158    }
159    Ok(crate::harness::bench_rows(m, &timings[0], &timings[1]))
160}
161
162/// Builds the extension and puts it beside the wrapper as `ruby/<lib>_native.so`.
163pub fn build(crate_dir: &Path, m: &Manifest) -> Result<PathBuf> {
164    let lib = crate::harness_c::build(crate_dir, m).map_err(explain_old_ruby)?;
165    let ext = if cfg!(target_os = "macos") {
166        "bundle"
167    } else {
168        "so"
169    };
170    let target = crate_dir.join(format!("ruby/{}_native.{ext}", m.lib_name()));
171    std::fs::create_dir_all(crate_dir.join("ruby"))?;
172    std::fs::copy(&lib, &target)?;
173    Ok(target)
174}
175
176/// rb-sys's error for a Ruby it has no stable API for: older than it supports, or newer.
177const NO_STABLE_API: &str = "Stable API is needed but could not find a candidate";
178
179/// rb-sys answers a Ruby it has no stable API for with a hint about its own features. When the
180/// Ruby it built against (`RUBY`, else `ruby`) is older than `doctor`'s minimum, this adds that
181/// cause and doctor's fix. Only a failed build gets it, so a Ruby chosen through `RUBY` or a
182/// version manager never stops a build that would work.
183fn explain_old_ruby(err: anyhow::Error) -> anyhow::Error {
184    if !err.to_string().contains(NO_STABLE_API) {
185        return err;
186    }
187    let mut cmd = version_probe();
188    // Not the caller's folder: rb-sys runs Ruby from its own, where a version manager's
189    // `.ruby-version` of the project does not apply.
190    let Ok(_scratch) = crate::harness::scratch_cwd(&mut cmd) else {
191        return err;
192    };
193    let banner = crate::process::output(&mut cmd, crate::process::QUICK)
194        .ok()
195        .filter(|out| out.success())
196        .map(|out| out.stdout_text());
197    old_ruby_note(err, banner.as_deref(), std::env::var_os("RUBY").is_some())
198}
199
200/// `ruby --version` for the Ruby rb-sys asks: `RUBY`, else `ruby`, without `RUBYOPT` as rb-sys
201/// runs it (an option the old Ruby rejects would make it fail before printing its version).
202fn version_probe() -> Command {
203    let mut cmd = Command::new(std::env::var_os("RUBY").unwrap_or_else(|| "ruby".into()));
204    cmd.arg("--version").env_remove("RUBYOPT");
205    cmd
206}
207
208/// `err` with the cause and doctor's fix when `banner` (`ruby --version`) is below the minimum.
209/// When `RUBY` chose that Ruby, installing another is not enough: `RUBY` has to change too.
210fn old_ruby_note(err: anyhow::Error, banner: Option<&str>, ruby_var: bool) -> anyhow::Error {
211    let (Some(banner), Some(min)) = (banner.map(str::trim), crate::doctor::minimum("ruby")) else {
212        return err;
213    };
214    if !crate::doctor::parse_version(banner).is_some_and(|v| v < min) {
215        return err;
216    }
217    let system = if cfg!(target_os = "macos") {
218        " (macOS's system Ruby is 2.6)"
219    } else {
220        ""
221    };
222    let fix = crate::doctor::install_command("ruby")
223        .map(|fix| format!("\nfix: {fix}"))
224        .unwrap_or_default();
225    let ruby_var = if ruby_var {
226        "\n`RUBY` is set, and rb-sys uses it before `ruby` on PATH: point it at the new Ruby, or unset it"
227    } else {
228        ""
229    };
230    anyhow::anyhow!(
231        "{err}\n\n{banner}: rust-anything needs Ruby {}.{}+{system}{fix}{ruby_var}",
232        min.0,
233        min.1
234    )
235}
236
237#[cfg(test)]
238mod tests {
239    use super::*;
240
241    fn failed() -> anyhow::Error {
242        anyhow::anyhow!(
243            "cargo build failed (exit status: 101):\n  Failed to setup stable API: {NO_STABLE_API}. \
244             Try enabling the `stable-api-compiled-fallback` feature in rb-sys."
245        )
246    }
247
248    #[test]
249    fn a_ruby_below_the_minimum_gets_the_cause_and_the_fix() {
250        let banner = "ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin26]";
251        let explained = old_ruby_note(failed(), Some(banner), false).to_string();
252        assert!(explained.starts_with("cargo build failed"), "{explained}");
253        assert!(
254            explained.contains(&format!("\n\n{banner}: rust-anything needs Ruby 3.0+")),
255            "{explained}"
256        );
257        let fix = crate::doctor::install_command("ruby").unwrap();
258        assert!(explained.ends_with(&format!("\nfix: {fix}")), "{explained}");
259    }
260
261    #[test]
262    fn a_newer_or_unknown_ruby_keeps_rb_sys_error() {
263        let plain = failed().to_string();
264        let newer = "ruby 4.1.0preview1 (2026-12-25 master 0123456789) +PRISM [arm64-darwin25]";
265        assert_eq!(
266            old_ruby_note(failed(), Some(newer), false).to_string(),
267            plain
268        );
269        assert_eq!(old_ruby_note(failed(), None, true).to_string(), plain);
270    }
271
272    #[test]
273    fn a_ruby_chosen_through_ruby_var_says_to_change_it() {
274        let banner = "ruby 2.6.10p210 (2022-04-12 revision 67958) [universal.arm64e-darwin26]";
275        let explained = old_ruby_note(failed(), Some(banner), true).to_string();
276        let fix = crate::doctor::install_command("ruby").unwrap();
277        assert!(
278            explained.ends_with(&format!(
279                "\nfix: {fix}\n`RUBY` is set, and rb-sys uses it before `ruby` on PATH: \
280                 point it at the new Ruby, or unset it"
281            )),
282            "{explained}"
283        );
284    }
285
286    #[test]
287    fn the_version_probe_drops_rubyopt_as_rb_sys_does() {
288        let probe = version_probe();
289        assert_eq!(probe.get_args().collect::<Vec<_>>(), ["--version"]);
290        assert!(
291            probe
292                .get_envs()
293                .any(|(key, value)| key == "RUBYOPT" && value.is_none()),
294            "{probe:?}"
295        );
296    }
297
298    #[test]
299    fn other_build_failures_are_left_alone() {
300        let failed = anyhow::anyhow!("cargo build failed (exit status: 101):\nerror[E0308]");
301        assert_eq!(
302            explain_old_ruby(failed).to_string(),
303            "cargo build failed (exit status: 101):\nerror[E0308]"
304        );
305    }
306}