Skip to main content

rust_anything/
harness_go.rs

1//! The Go side of record, build, diff and bench. A generated driver calls the package's
2//! functions by name: built against the original package to record, and against the cgo
3//! wrapper over the Rust library to diff. Both builds are separate modules under `.rust-anything/`
4//! with `replace` directives, so nothing is written into the original repository.
5
6use crate::walk::Canonical;
7use std::path::{Path, PathBuf};
8use std::process::Command;
9
10use anyhow::{Context, Result, bail};
11use serde_json::Value;
12
13use crate::bridge::Manifest;
14use crate::harness::{BenchRow, CASES, DiffOutcome};
15
16const WORK_DIR: &str = ".rust-anything";
17
18fn run(cmd: &mut Command, what: &str) -> Result<()> {
19    let _scratch = crate::harness::scratch_cwd(cmd)?;
20    let output = cmd.output().with_context(|| format!("running {what}"))?;
21    if !output.status.success() {
22        let stderr = String::from_utf8_lossy(&output.stderr);
23        let tail: Vec<&str> = stderr.lines().rev().take(30).collect();
24        bail!(
25            "{what} failed ({}):\n{}",
26            output.status,
27            tail.into_iter().rev().collect::<Vec<_>>().join("\n")
28        );
29    }
30    Ok(())
31}
32
33/// The folder of the unit's package.
34fn unit_dir(m: &Manifest) -> PathBuf {
35    let dir = m.root.join(m.unit.trim_end_matches('/'));
36    if dir.is_file() {
37        dir.parent().map(Path::to_path_buf).unwrap_or(dir)
38    } else {
39        dir
40    }
41}
42
43/// The module that holds the unit: its folder, `go.mod` text and module path.
44fn module_of(m: &Manifest) -> Result<(PathBuf, String, String)> {
45    let mut dir = unit_dir(m);
46    loop {
47        let go_mod = dir.join("go.mod");
48        if go_mod.exists() {
49            let text = std::fs::read_to_string(&go_mod)?;
50            let path = crate::lang::go::module_path(&text)
51                .with_context(|| format!("no `module` line in {}", go_mod.display()))?;
52            return Ok((dir, text, path));
53        }
54        if !dir.pop() {
55            bail!("no go.mod above {}", unit_dir(m).display());
56        }
57    }
58}
59
60/// The import path of the unit's package.
61pub fn import_path(m: &Manifest) -> Result<String> {
62    let (dir, _, module) = module_of(m)?;
63    let rel = unit_dir(m)
64        .strip_prefix(&dir)
65        .map(|r| r.to_string_lossy().replace('\\', "/"))
66        .unwrap_or_default();
67    Ok(if rel.is_empty() {
68        module
69    } else {
70        format!("{module}/{rel}")
71    })
72}
73
74fn go_version(go_mod: &str) -> &str {
75    crate::lang::go::mod_directive(go_mod, "go").unwrap_or("1.21")
76}
77
78/// The wrapper module's path.
79pub fn wrapper_module(m: &Manifest) -> String {
80    format!("rust-anything.local/{}", m.lib_name())
81}
82
83pub fn wrapper_go_mod(m: &Manifest) -> String {
84    format!("module {}\n\ngo 1.21\n", wrapper_module(m))
85}
86
87fn go() -> Command {
88    let mut cmd = Command::new("go");
89    cmd.env("GOWORK", "off").env("GOFLAGS", "-mod=mod");
90    cmd
91}
92
93/// A local replacement still requires a version compatible with the module path.
94fn local_module_version(module: &str) -> String {
95    let suffix = if module.starts_with("gopkg.in/") {
96        module.trim_end_matches("-unstable").rsplit_once(".v")
97    } else {
98        module.rsplit_once("/v")
99    };
100    suffix
101        .and_then(|(_, major)| major.parse::<u64>().ok())
102        .map_or_else(|| "v0.0.0".into(), |major| format!("v{major}.0.0"))
103}
104
105/// Writes and builds a driver module for the original (`rust: false`) or the wrapper.
106fn build_driver(crate_dir: &Path, m: &Manifest, rust: bool) -> Result<PathBuf> {
107    let crate_dir = &crate_dir.canonical()?;
108    let (module_dir, go_mod, module) = module_of(m)?;
109    let name = if rust { "go-rust" } else { "go-original" };
110    let dir = crate_dir.join(WORK_DIR).join(name);
111    std::fs::create_dir_all(&dir)?;
112    let (target_module, target_dir, import) = if rust {
113        (
114            wrapper_module(m),
115            crate_dir.join("go").canonical()?,
116            wrapper_module(m),
117        )
118    } else {
119        (module.clone(), module_dir.clone(), import_path(m)?)
120    };
121    let driver_module = format!("{target_module}/rust-anything-driver");
122    let mut text = format!(
123        "module {driver_module}\n\ngo {}\n\nrequire {target_module} {}\n\nreplace {target_module} => {}\n",
124        go_version(&go_mod),
125        local_module_version(&target_module),
126        serde_json::to_string(&target_dir.to_str().context("Go module path is not UTF-8")?)?
127    );
128    if rust {
129        // The wrapper copies the original's types only; it needs nothing from the original module.
130        text.push('\n');
131    }
132    std::fs::write(dir.join("go.mod"), text)?;
133    // The original's checksums let its dependencies resolve without editing its go.sum.
134    if let Ok(sum) = std::fs::read_to_string(module_dir.join("go.sum")) {
135        std::fs::write(dir.join("go.sum"), sum)?;
136    }
137    std::fs::write(dir.join("main.go"), crate::codegen_go::driver(m, &import))?;
138    if rust {
139        let stale = crate_dir
140            .join("target/release")
141            .join(format!("lib{}.a", m.lib_name()));
142        if stale.is_file() {
143            std::fs::remove_file(&stale)
144                .with_context(|| format!("removing {}", stale.display()))?;
145        }
146    }
147    let bin = dir.join("driver");
148    let mut command = go();
149    command
150        .args(["build", "-o"])
151        .arg(&bin)
152        .arg(".")
153        .current_dir(&dir);
154    if rust {
155        command.env("CGO_ENABLED", "1");
156    }
157    run(
158        &mut command,
159        if rust {
160            "go build (driver over the Rust wrapper)"
161        } else {
162            "go build (driver over the original package)"
163        },
164    )?;
165    Ok(bin)
166}
167
168/// The driver built over the Rust wrapper loads the port's shared library. Windows finds a DLL
169/// through `PATH`, not a path recorded in the binary, so its folder goes first there.
170fn driver_command(crate_dir: &Path, bin: &Path) -> Command {
171    let mut cmd = Command::new(bin);
172    if cfg!(windows) {
173        let mut dirs = vec![crate_dir.join("target").join("release")];
174        dirs.extend(std::env::split_paths(
175            &std::env::var_os("PATH").unwrap_or_default(),
176        ));
177        if let Ok(path) = std::env::join_paths(dirs) {
178            cmd.env("PATH", path);
179        }
180    }
181    cmd
182}
183
184pub fn record(crate_dir: &Path, m: &Manifest, cases: &[Value]) -> Result<PathBuf> {
185    let bin = build_driver(crate_dir, m, false)?;
186    let slim: Vec<Value> = cases
187        .iter()
188        .map(|c| serde_json::json!({ "fn": c["fn"], "args": c["args"] }))
189        .collect();
190    let out = crate_dir.join(CASES);
191    crate::harness::record_cases(
192        &slim,
193        &crate_dir.join(WORK_DIR),
194        &out,
195        "Go driver (record)",
196        |inputs, part| {
197            let mut cmd = Command::new(&bin);
198            cmd.arg("record").arg(inputs).arg(part);
199            Ok(cmd)
200        },
201    )?;
202    Ok(out)
203}
204
205pub fn diff(crate_dir: &Path, m: &Manifest) -> Result<DiffOutcome> {
206    let cases = crate_dir.join(CASES);
207    if !cases.exists() {
208        bail!(
209            "no {CASES} in {} (run `rust-anything record` first)",
210            crate_dir.display()
211        );
212    }
213    crate::harness_c::built_library(crate_dir, m)?;
214    let bin = build_driver(crate_dir, m, true)?;
215    let out = crate_dir.join(WORK_DIR).join("diff.json");
216    run(
217        driver_command(crate_dir, &bin)
218            .arg("diff")
219            .arg(&cases)
220            .arg(&out),
221        "Go driver (diff)",
222    )?;
223    Ok(serde_json::from_str(&std::fs::read_to_string(&out)?)?)
224}
225
226pub fn bench(crate_dir: &Path, m: &Manifest, min_ms: u64) -> Result<Vec<BenchRow>> {
227    let cases = crate_dir.join(CASES);
228    if !cases.exists() {
229        bail!(
230            "no {CASES} in {} (run `rust-anything record` first)",
231            crate_dir.display()
232        );
233    }
234    crate::harness_c::built_library(crate_dir, m)?;
235    let mut timings = Vec::new();
236    for rust in [false, true] {
237        let bin = build_driver(crate_dir, m, rust)?;
238        let out = crate_dir.join(WORK_DIR).join(if rust {
239            "bench-rust.json"
240        } else {
241            "bench-original.json"
242        });
243        run(
244            driver_command(crate_dir, &bin)
245                .arg("bench")
246                .arg(&cases)
247                .arg(&out)
248                .arg(min_ms.to_string()),
249            "Go driver (bench)",
250        )?;
251        let parsed: serde_json::Map<String, Value> =
252            serde_json::from_str(&std::fs::read_to_string(&out)?)?;
253        timings.push(parsed);
254    }
255    Ok(crate::harness::bench_rows(m, &timings[0], &timings[1]))
256}
257
258#[cfg(test)]
259mod tests {
260    use super::*;
261
262    #[test]
263    fn local_module_version_follows_the_major_version_in_the_path() {
264        for (module, version) in [
265            ("example.com/m", "v0.0.0"),
266            ("example.com/m/v2", "v2.0.0"),
267            ("gopkg.in/yaml.v3", "v3.0.0"),
268            ("gopkg.in/check.v1-unstable", "v1.0.0"),
269            ("example.com/v2ray", "v0.0.0"),
270        ] {
271            assert_eq!(local_module_version(module), version, "{module}");
272        }
273    }
274}