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