1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
//! # bf-lib
//!
//! `bf-lib` is small library to run brainfuck programs non-interactively
//!
//! The entry point is the [`Exec`] struct, stole the idea from [`subprocess`]
//!
//! [`subprocess`]: https://crates.io/crates/subprocess

use std::{error, fmt, time, path::PathBuf};

/// Possible errors encountered while running the program.
#[derive(Debug)]
pub enum Error {
    Compile(String),
    Runtime(RuntimeError),
    Subprocess(subprocess::PopenError),
    Syntax(usize),
    Timeout,
}

impl error::Error for Error {}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let pre = "Error, I didn't quite get that.\n";
        match self {
            Error::Compile(s) => write!(f, "{}rustc error: {}", pre, s),
            Error::Runtime(e) => write!(f, "{}Runtime error: {}", pre, e),
            Error::Subprocess(e) => write!(f, "{}rustc error: {}", pre, e),
            Error::Syntax(p) => write!(f, "{}Unmatched bracket at {}.", pre, p),
            Error::Timeout => write!(f, "{}Executable timed out.", pre),
        }
    }
}

/// Possible runtime errors encountered while running the program.
#[derive(Debug, PartialEq)]
pub enum RuntimeError {
    OutOfMemoryBounds,
    InputTooShort,
    Signal,
}

impl fmt::Display for RuntimeError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            RuntimeError::OutOfMemoryBounds => write!(f, "access memory out of bounds"),
            RuntimeError::InputTooShort => write!(f, "input was not long enough"),
            RuntimeError::Signal => write!(f, "executable was probably killed by a signal"),
        }
    }
}

/// Interface for running brainfuck code.
///
/// The [`prog`] method returns an instance with the default options (no timeout, input or
/// temporary file path)
///
/// [`input`], [`timeout`] and [`tmpdir`] are used to change the default values, the program can
/// then be run by calling [`run`], [`transpile`] or [`interpret`].
///
/// [`prog`]: struct.Exec.html#method.prog
/// [`input`]: struct.Exec.html#method.input
/// [`timeout`]: struct.Exec.html#method.timeout
/// [`tmpdir`]: struct.Exec.html#method.tmpdir
/// [`run`]: struct.Exec.html#method.run
/// [`transpile`]: struct.Exec.html#method.transpile
/// [`interpret`]: struct.Exec.html#method.interpret
/// ```
/// # use bf_lib::Exec;
/// let prog = "++++++++++[>++++++++++>+++++++++++<<-]>++.>+..";
/// let output = Exec::prog(prog).run().unwrap();
///
/// assert_eq!(String::from("foo"), output);
/// ```
pub struct Exec {
    program: String,
    input: Option<String>,
    time: Option<time::Duration>,
    tmp_path: Option<PathBuf>,
}

impl Exec {
    /// Contructs a new `Exec`, configured to run `prog`.
    /// By default it will be run without input, timeout or temporary file path (defaults to cwd).
    pub fn prog(prog: &str) -> Exec {
        Exec {
            program: String::from(prog),
            input: None,
            time: None,
            tmp_path: None,
        }
    }

    /// Sets the input for the program.
    pub fn input(self, input: Option<String>) -> Exec {
        Exec {
            input,
            ..self
        }
    }

    /// Sets the timeout for the program.
    pub fn timeout(self, time: Option<time::Duration>) -> Exec {
        Exec {
            time,
            ..self
        }
    }

    /// Sets the temporary file path for the transpiler.
    pub fn tmpdir(self, tmp_path: Option<PathBuf>) -> Exec {
        Exec {
            tmp_path,
            ..self
        }
    }
    
    /// Wrapper for the [`transpile`] and [`interpret`] methods:
    /// uses the faster transpiler when rustc is detected, falls back to interpreting the code.
    ///
    /// [`transpile`]: struct.Exec.html#method.interpret
    /// [`interpret`]: struct.Exec.html#method.transpile
    pub fn run(self) -> Result<String, Error> {
        bf::run(&self.program, self.input, self.time, self.tmp_path)
    }
    
    /// Runs the program with the interpreter, returning the output or an [`Error`].
    pub fn interpret(self) -> Result<String, Error> {
        bf::interpreter::run(&self.program, self.input, self.time)
    }
    
    /// Runs the program with the transpiler, returning the output or an [`Error`].
    ///
    /// Needs read and write permission in the chosen temporary file folder.
    pub fn transpile(self) -> Result<String, Error> {
        bf::transpiler::run(&self.program, self.input, self.time, self.tmp_path)
    }

    /// Translated the program to rust code
    pub fn translate(&self) -> Result<String, Error> {
        bf::transpiler::translate(&self.program, self.input.clone())
    }
}

/// Looks for unmatched brackets
///
/// ```
/// let ok = "+[+]";
/// let err = "[[]";
/// bf_lib::check_brackets(ok).unwrap();
/// bf_lib::check_brackets(err).unwrap_err();
/// ```
pub fn check_brackets(prog: &str) -> Result<(), Error> {
    let mut open: Vec<usize> = Vec::new();
    for (i, b) in prog.as_bytes().iter().enumerate() {
        match b {
            b'[' => open.push(i),
            b']' => {
                if let None = open.pop() {
                    return Err(Error::Syntax(i));
                };
            }
            _ => (),
        }
    }
    if open.len() != 0 {
        Err(Error::Syntax(open.pop().unwrap()))
    } else {
        Ok(())
    }
}

/// Checks if the program will try to read user input.
///
/// ```
/// let reads = ",[>+>+<<-]>.>.";
/// let does_not_read = "foo. bar.";
///
/// assert_eq!(true, bf_lib::wants_input(reads));
/// assert_eq!(false, bf_lib::wants_input(does_not_read));
/// ```
pub fn wants_input(program: &str) -> bool {
    program.contains(",")
}

mod bf;

#[cfg(test)]
mod tests;