use crate::host::{self, StdinSource};
pub(crate) struct ExitNow(pub i32);
pub fn run_program(src: &str, input: &str) -> Result<String, String> {
let src = src.to_owned();
let stdin = StdinSource::Fed(std::io::Cursor::new(input.as_bytes().to_vec()));
crate::with_interpreter_stack(move || {
let run = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
host::with_host(|h| {
h.stdin = stdin;
h.capture = Some(String::new());
});
crate::eval_str(&src).map_err(|e| crate::format_error(&e))
}));
let output = host::with_host(|h| h.capture.take()).unwrap_or_default();
match run {
Ok(Ok(_)) => Ok(output),
Ok(Err(e)) => Err(e),
Err(panic) => match panic.downcast::<ExitNow>() {
Ok(exit) if exit.0 == 0 => Ok(output),
Ok(exit) => Err(format!("kill-emacs: exit status {}", exit.0)),
Err(panic) => Err(panic_message(panic.as_ref())),
},
}
})
}
fn panic_message(panic: &(dyn std::any::Any + Send)) -> String {
let msg = panic
.downcast_ref::<&str>()
.copied()
.or_else(|| panic.downcast_ref::<String>().map(String::as_str))
.unwrap_or("unknown panic");
format!("interpreter panicked: {msg}")
}