Skip to main content

gp_runtime/
lib.rs

1//! # PARI/GP
2//! 
3//! This crate is meant to be used using a `gp!{}` macro and added to your project using the
4//! `pari-gp` crate. Nevertheless, if you don't want to use the macro and you only want to run
5//! `gp` code with &str inputs, feel free to just import this crate.
6
7use std::{io::Write, process::{Command, Stdio}};
8
9pub use gp_type::{FromGp, IntoGp, ParseError};
10mod gp_type;
11
12pub use gp_error::GpError;
13mod gp_error;
14
15pub fn try_from_gp<'s, T: FromGp>(input: &'s str) -> Result<T, ParseError<'s>> {
16    FromGp::try_from(input).map(|(out, _)| out)
17}
18
19pub fn run(code: &str) -> Result<String, GpError> {
20    let mut command = Command::new("gp");
21    
22    command
23        .arg("-q")
24        .args(["-D", "histfile=\"\""])
25        .stdin(Stdio::piped())
26        .stderr(Stdio::piped())
27        .stdout(Stdio::piped());
28
29    let mut child = match command.spawn() {
30        Ok(spawned) => spawned,
31        Err(err) => {
32            let errmsg = match err.kind() {
33                std::io::ErrorKind::NotFound => "Could not find `gp` on PATH. Install PARI/GP externally and make sure it's path is set in the PATH environment variable.".to_string(),
34                _ => format!("Could not start PARI/GP due to an unknown error: {err}"),
35            };
36
37            return Err(GpError::Any(errmsg));
38        }
39    };
40
41    child.stdin.as_mut().unwrap().write_all(code.as_bytes()).unwrap();
42    let output = child.wait_with_output().unwrap();
43    let stdout = String::from_utf8(output.stdout).unwrap();
44    let stderr = String::from_utf8(output.stderr).unwrap();
45
46    if !stderr.trim().is_empty() {
47        Err(GpError::from_stderr(stderr))
48    } else {
49        Ok(stdout)
50    }
51}