Skip to main content

arb/
embed.rs

1//! Running an arb spec from a host program, without a process or a terminal.
2//!
3//! [`run_program`] is `printf %s INPUT | arb -e SRC | cat`: the same headless
4//! path the binary takes when its stdin and stdout are both pipes and no
5//! terminal is reachable (`cli::run_headless`). An `out { … }` pipeline
6//! reshapes the input, a spec with no `out` passes the input through, and a
7//! spec that reads no stream prints its widget summary.
8
9use std::io::{ErrorKind, Write};
10
11/// Stack for the thread a run executes on: jq programs recurse as deep as
12/// they like (see the `arb` binary's `main`, which reserves the same). The
13/// reservation is virtual; pages are only touched by a program that recurses.
14const STACK_BYTES: usize = 4 << 30;
15
16/// Run `src` as a complete program with `input` as its stdin and return
17/// everything it wrote to stdout.
18///
19/// `src` is spec text, as `arb -e SRC` takes it. Each call builds the spec
20/// from scratch on a fresh thread, so nothing carries over between calls and
21/// concurrent calls write to their own buffers. A run that ends with a nonzero
22/// status (a spec error, a jq error, `halt_error`, a panic) returns `Err` with
23/// what arb wrote to stderr, or `exit status N` when it wrote nothing; a run
24/// that ends with status 0, including jq's `halt`, returns `Ok` with the
25/// output produced so far.
26pub fn run_program(src: &str, input: &str) -> Result<String, String> {
27    let (src, input) = (src.to_owned(), input.to_owned());
28    let run = move || run_here(&src, &input);
29    std::thread::Builder::new()
30        .stack_size(STACK_BYTES)
31        .spawn(run)
32        .map_err(|e| format!("arb: cannot start the run thread: {e}"))?
33        .join()
34        .unwrap_or_else(|_| Err("arb: run panicked".to_string()))
35}
36
37/// One run on the current thread. [`crate::hosted::run`] turns arb's `exit`
38/// calls and panics into a status instead of ending the process.
39fn run_here(src: &str, input: &str) -> Result<String, String> {
40    let (mut out, mut err) = (Vec::new(), Vec::new());
41    let status = crate::hosted::run(|| {
42        match crate::cli::run_headless(src, input.as_bytes(), &mut out, &mut err) {
43            Ok(()) => 0,
44            Err(e) if e.kind() == ErrorKind::BrokenPipe => 0,
45            Err(e) => {
46                let _ = writeln!(err, "arb: {e}");
47                1
48            }
49        }
50    });
51    if status == 0 {
52        return Ok(String::from_utf8_lossy(&out).into_owned());
53    }
54    let msg = String::from_utf8_lossy(&err).trim_end().to_string();
55    Err(if msg.is_empty() {
56        format!("exit status {status}")
57    } else {
58        msg
59    })
60}