libbfi/
runtime.rs

1#![doc = r"Traits and definitions for building a brainfuck interpreter"]
2#![cfg_attr(docsrs, feature(doc_cfg))]
3
4//! Sharing memory should work like this:
5//! let env = BrainfuckRuntime::new().add_tokens(program).run_full_stack().clean_env()
6//! let runtime = BoofRuntime::new().add_tokens(program);
7//! runtime.memory = env.memory;
8//! runtime.run_full_stack().clean_env()
9
10use crate::token::BFToken;
11use std::{io::BufRead, io::Write};
12
13pub trait Operator {
14    fn op_ptr_left(&mut self);
15    fn op_ptr_right(&mut self);
16    fn op_add_to_cell(&mut self);
17    fn op_sub_from_cell(&mut self);
18    fn op_print_cell_as_char(&self, writer: &mut impl Write);
19    fn op_input_to_cell(&mut self, reader: &mut impl BufRead);
20    fn op_jump_forwards(&mut self);
21    fn op_jump_backwards(&mut self);
22}
23
24pub trait Runner: Clone + Sized {
25    /// Adds a sequence of tokens (instructions) to the runtime's instruction stack.
26    fn add_tokens(&mut self, token_stream: Vec<BFToken>) -> &mut Self;
27    /// Resets the runtime environment to its initial state: instruction and pointer are set to zero,
28    /// memory is cleared (all cells set to 0), and the instruction stack is emptied.
29    fn clean_env(&mut self) -> &mut Self;
30    /// Executes the next instruction from the instruction stack.
31    fn next_instruction(&mut self, reader: &mut impl BufRead, writer: &mut impl Write)
32        -> &mut Self;
33    /// Executes all instructions in the stack until the end is reached.
34    fn run_full_stack(&mut self, reader: &mut impl BufRead, writer: &mut impl Write) -> &mut Self;
35}