diff options
| author | Sophie Forrest <git@sophieforrest.com> | 2024-08-30 23:35:45 +1200 |
|---|---|---|
| committer | Sophie Forrest <git@sophieforrest.com> | 2024-08-30 23:35:45 +1200 |
| commit | 5126c9ed83fe6169463566e74f966a4a63e57ca0 (patch) | |
| tree | 99be8b093f6736eba59c529300519985d9c1c5c6 /src/utility.rs | |
feat: initial commit of brainf interpreter
Diffstat (limited to 'src/utility.rs')
| -rw-r--r-- | src/utility.rs | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/src/utility.rs b/src/utility.rs new file mode 100644 index 0000000..a903273 --- /dev/null +++ b/src/utility.rs @@ -0,0 +1,47 @@ +//! Utility functions for working with the Brainfuck interpreter. + +use std::path::Path; + +use crate::{constants::TapeInner, execute, lex, parse, Error}; + +/// Utility function to execute a Brainfuck file. Lexes, parses and executes the +/// input file. +/// +/// # Errors +/// +/// This function will return an error if reading the input file, parsing or +/// execution fails. See documentation for [`crate::parser::parse`] and +/// [`crate::executor::execute`]. +pub fn execute_from_file(path: impl AsRef<Path>, tape: &mut [TapeInner]) -> Result<(), Error> { + let input = fs_err::read_to_string(path.as_ref())?; + + let operator_codes = lex(&input); + + let instructions = parse(&input, &operator_codes)?; + + let mut data_pointer = 0; + + execute(&instructions, tape, &mut data_pointer)?; + + Ok(()) +} + +/// Utility function to execute Brainfuck code. Lexes, parses and executes the +/// input. +/// +/// # Errors +/// +/// This function will return an error if parsing or +/// execution fails. See documentation for [`crate::parser::parse`] and +/// [`crate::executor::execute`]. +pub fn execute_from_str(input: &str, tape: &mut [TapeInner]) -> Result<(), Error> { + let operator_codes = lex(input); + + let instructions = parse(input, &operator_codes)?; + + let mut data_pointer = 0; + + execute(&instructions, tape, &mut data_pointer)?; + + Ok(()) +} |